cztchoice
1/22/2014 - 1:27 PM

Balanced Binary Tree http://oj.leetcode.com/problems/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:
    bool isBalanced(TreeNode *root) {
        if(root == NULL){
            return true;
        }
        if(depth(root) != -1){
            return true;
        }
        else{
            return false;
        }
    }
    int depth(TreeNode *root){
        if(root == NULL){
            return 0;
        }
        if(root->left == NULL && root->right == NULL){
            return 1;
        }
        int left = depth(root->left);
        int right = depth(root->right);
        if(left == -1 || right == -1 || left - right > 1 ||right - left > 1){
            return -1;
        }
        else{
            return (left > right) ? left + 1 : right + 1;
        }
    }
};