您的位置:首页 > 其它

[Leetcode 110, Easy] Balanced Binary Tree

2015-02-23 12:32 357 查看
Problem:

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.
Analysis:
This is a straightforward verification of the construction of binary search trees. We have:

(1) we verify the construction recursively, i.e., every possible subtrees should satisfy the requirement.Note: A tree which has an unbalance subtree may have the difference between the longest and the shortest
path less than 2.

(2) the depth of a subtree is size of the longer path between that of the left subtree and that of the right subtree of this subtree.

Solutions:

C++:

int GetSubtreeDepth(TreeNode* local_root)
    {
        int left_depth = 0;
        if(local_root->left)
            left_depth = GetSubtreeDepth(local_root->left);
        if(left_depth == -1)
            return -1;
        
        int right_depth = 0;
        if(local_root->right)
            right_depth = GetSubtreeDepth(local_root->right);
        if(right_depth == -1)
            return -1;
            
        if(abs(left_depth - right_depth) > 1)
            return -1;

        return (left_depth >= right_depth ? left_depth + 1 : right_depth + 1);
    }

    bool isBalanced(TreeNode *root) {
        if(root == NULL)
            return true;

        int left_depth = 0;
        if(root->left)
            left_depth = GetSubtreeDepth(root->left);
        if(left_depth == -1)
            return false;
        
        int right_depth = 0;
        if(root->right)
            right_depth = GetSubtreeDepth(root->right);
        if(right_depth == -1)
            return false;

        return (abs(left_depth - right_depth) <= 1);
    }


Java:

Python:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: