Sunday, September 1, 2013

Balanced Binary Search 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 ofevery node never differ by more than 1.
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:

bool isBalanced(TreeNode *root, int &ht)
{
    if(!root)
    {
        ht  = 0;
        return true;
    }
    
    int left, right;
    bool lh, rh;
    
    lh  = isBalanced(root->left, left);
    rh  = isBalanced(root->right, right);
    
    ht  = 1  + max(left, right);
    
    if(lh && rh)
    {
        if(abs(left - right) <= 1)
            return true;
        else
            return false;
    }
    
    return false;
}

bool isBalanced(TreeNode *root) {

    int x;
    return isBalanced(root, x);
}
};

No comments:

Post a Comment