Balanced Binary Tree

时间:2015-01-30 16:08:22   收藏:0   阅读:149

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 of every node never differ by more than 1.


class Solution {
public:
    bool is_balanced = true;
    int checkHieght(TreeNode *root) {
        int lh = 0, rh = 0;
        if(root == NULL || is_balanced == false) return 0;
        if(root->left != NULL && is_balanced == true) 
            lh = checkHieght(root->left) + 1;
        if(root->right != NULL && is_balanced == true) 
            rh = checkHieght(root->right) + 1;
        if(abs(lh - rh) > 1) is_balanced = false;
        return lh > rh ? lh : rh;
    }
    bool isBalanced(TreeNode *root) {
        checkHieght(root);
        return is_balanced;
    }
};


评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!