美文网首页
[leetcode] 110. Balanced Binary

[leetcode] 110. Balanced Binary

作者: 叶孤陈 | 来源:发表于2017-06-11 15:25 被阅读0次

    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.

    解题思路:

    本题求一个树是否是平衡树。可以采用深度优先遍历,计算树的高度,如果左右子树高度差超过1,则返回-1 .

    class Solution {
    public:
        int isBalancedHelper(TreeNode* root)
        {
            if(root == NULL) return 0;
            int leftHeight = isBalancedHelper(root->left);
            if(leftHeight == -1) return -1;
            
            int rightHeight = isBalancedHelper(root->right);
            if(rightHeight == -1) return -1;
            
            if(abs(leftHeight - rightHeight) > 1) return -1;
            return max(leftHeight,rightHeight) + 1;
        }
        bool isBalanced(TreeNode* root) {
            return isBalancedHelper(root) != -1;
        }
    };
    

    相关文章

      网友评论

          本文标题:[leetcode] 110. Balanced Binary

          本文链接:https://www.haomeiwen.com/subject/ddmhqxtx.html