Doing something you intrinsically are enthusiastic with.

2016年10月26日 星期三

Leetcode-Balanced Binary Tree

晚上9:34 Posted by Unknown No comments
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.
=======================================================================
Solution :
The Top-down solution is to check all the sub tress from the root whether
the difference of the two sub tress more than 1.

class solution {
public:
    int depth (TreeNode *root) {
        if (root == NULL) return 0;
        return max (depth(root -> left), depth (root -> right)) + 1;
    }

    bool isBalanced (TreeNode *root) {
        if (root == NULL) return true;
        
        int left=depth(root->left);
        int right=depth(root->right);
        
        return abs(left - right) <= 1 && isBalanced(root->left) && isBalanced(root->right);
    }
};

0 意見:

張貼留言