leetcode由易入难——【2】Balanced Binary Tree

本文深入探讨了平衡二叉树的概念及其在计算机科学中的应用,详细介绍了如何使用深度优先搜索(DFS)来判断给定二叉树是否为平衡二叉树,通过实例分析了平衡二叉树的特性及其实现方式。

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees ofevery node never differ by more than 1.


1. Balanced Binary Tree(平衡二叉树)

    平衡二叉树又被称为AVL树(有别于AVL算法),且具有以下性质:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。常用算法有红黑树、AVL、Treap、伸展树等。在平衡二叉搜索树中,我们可以看到,其高度一般都良好地维持在O(log2n),大大降低了操作的时间复杂度。

2. DFS(Depth-First-Search,深度优先搜索)

    深度优先搜索属于图算法的一种,其过程简要来说是对每一个可能的分支路径深入到不能再深入为止,而且每个节点只能访问一次。


// 时间复杂度O(n),空间复杂度O(logn)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isBalanced(TreeNode* root) {
        return balancedHeight (root) >= 0;
    }
    
    //Return the height of 'root' if 'root' is a balanced tree,
    //otherwise, returns '-1'.
    int balancedHeight (TreeNode* root){
        if (root == nullptr) return 0;
        int left = balancedHeight (root->left);
        int right = balancedHeight (root->right);
        
        if (left < 0 || right < 0 || abs(left - right) > 1) return -1;
        
        return max(left, right) + 1;
    }
    
};






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值