Implement a function to check if a tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that no two leaf nodes differ in distance from the root by more than one.

 1 int d=0,min=INT_MAX,max = INT_MIN;
 2 
 3 void GetMaxAndMin(Node *root)
 4 {
 5     if(!root->left&&!root->right)
 6     {
 7         min = d<min? d:min;
 8         max = d>max? d:max;
 9         return;
10     }    
11     ++d;
12     if(root->left)  GetMaxAndMin(root->left);
13     if(root->right) GetMaxAndMin(root->right);
14     d--;
15 }
16 
17 bool isBVT(Node *root)
18 {
19     if(!root) return true;    
20     GetMaxAndMin(root);    
21     if(max-min)<=1)
22         return true;
23     else
24         return false;
25 }

 

 

 

 posted on 2013-08-07 13:21  xuanxu  阅读(132)  评论(0编辑  收藏  举报