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 class Solution {
 2 public:
 3     int maxDepth(TreeNode * root)
 4     {    
 5         if(root==NULL)
 6             return 0;
 7         if(root&&root->left==NULL&&root->right==NULL) return 1;
 8         int i=1;
 9         int j=1;
10         i=maxDepth(root->left);
11         j=maxDepth(root->right);
12         
13         if(i>j)
14             return i+1;
15          else
16             return j+1;
17         
18     }
19     bool isBalanced(TreeNode *root) {
20         if(root==NULL) return 1;
21         
22         int leftDepth=maxDepth(root->left);
23         int rightDepth=maxDepth(root->right);
24 
25         if(leftDepth-rightDepth>1||leftDepth-rightDepth<-1)
26             return false;
27         else
28             return isBalanced(root->left)&&isBalanced(root->right);
29     }
30 };

 

posted on 2015-04-26 21:41  黄瓜小肥皂  阅读(140)  评论(0编辑  收藏  举报