Sunday, October 28, 2012

Balanced Binary Tree

/**
 * 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 height (TreeNode *root) {
        if (root == NULL)
            return 0;
        else
            return max(height(root -> left), height(root -> right)) + 1;
    }
   
    bool isBalanced(TreeNode *root) {
        if (root == NULL)
            return true;
        else if ((abs(height(root -> left) - height(root -> right)) < 2) &&
                isBalanced(root -> left) && isBalanced(root -> right))
            return true;
        return false;
    }
};

No comments:

Post a Comment