4.4 Check Balanced

Balanced Binary Tree:
1. The left and right subtree’s height differ by at most one, AND
2. The left subtree is balanced, AND
3. The right subtree is balance.

According to above definition, we have both O(nlogn) and O(n) method to solve this problem.

O(nlogn): this method touched all nodes in BT.

    int getHeight(TreeNode* root){
        if(!root) return 0;
        return max(getHeight(root->left), getHeight(root->right)) + 1;
    }
    bool isBalanced(TreeNode* root){
        if(!root) return true;
        int diff = abs(getHeight(root->left) - getHeight(root->right));
        if(diff > 1) return false;
        else return isBalanced(root->left) && isBalanced(root->right);
    }

O(n):

    int checkHeight(TreeNode* root){
        if(!root) return 0;
        int left = checkHeight(root->left);
        if(left == -1) return -1;
        int right = checkHeight(root->right);
        if(right == -1) return -1;
        int diff = abs(left - right);
        if(diff > 1) return -1;
        else return max(left,right) + 1;
    }
    bool isBalanced(TreeNode* root){
        if(checkHeight(root) == -1) return false;
        else return true;
    }
    bool isBalancedHepler(TreeNode* root, int& depth){
        if(!root) {
            depth = 0;
            return true;
        }
        int left, right;
        // Notice, the logic operation is shortcut
        // once the left tree is judged to be unbalanced, then the right tree will not be judged
        if(isBalancedHepler(root->left, left) && isBalancedHepler(root->right, right) && abs(left - right)<2){
            depth = max(left,right) + 1;
            return true;
        }
        else return false;
    }

    bool isBalanced(TreeNode *root) {
        // write your code here
        int height;
        return isBalancedHepler(root, height);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值