Thursday, September 25, 2014

[Leetcode] Balanced Binary Tree

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:

Try to get the tree height and do the balance comparison in the same function to be more efficient.

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:

    int helper(TreeNode *root, bool& isBalanced)
    {
        if (root == NULL)
            return 0;
        else
        {
            int leftHeight = helper(root->left, isBalanced);
            int rightHeight = helper(root->right, isBalanced);
            if (abs(leftHeight - rightHeight) > 1)
                isBalanced = false;
                
            return max(leftHeight, rightHeight) + 1;
        }
    }

    bool isBalanced(TreeNode *root) {
        bool isBalanced = true;
        helper(root, isBalanced);
        return isBalanced;
    }
};

No comments:

Post a Comment