2016年2月11日 星期四

LEET code -- 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.

去找底下樹的高度就好

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
bool isBalanced(struct TreeNode* root) {
    int ans=treehigh(root);
    return ans!=-1? true:false;
    
}
int treehigh(struct TreeNode * root){
    if(root==NULL)return 1;
    int le=treehigh(root->left);
    int ri=treehigh(root->right);
    if (le==-1 || ri==-1 || abs(le-ri)>1 )return -1;
    else return le>=ri? 1+le:1+ri;
}

沒有留言:

張貼留言