@@ -25,21 +25,51 @@ class Solution {
2525public:
2626 bool isBalanced (TreeNode *root) {
2727 int height=0 ;
28- return isBalancedUtil (root,& height);
28+ return isBalancedUtil (root, height);
2929 }
30- bool isBalancedUtil (TreeNode* root,int *height){
30+
31+ bool isBalancedUtil (TreeNode* root, int & height){
3132 if (root==NULL ){
32- * height=0 ;
33- return 1 ;
33+ height=0 ;
34+ return true ;
3435 }
35- int lh=0 ,rh=0 ;
36- bool isLeft,isRight;
37- isLeft=isBalancedUtil (root->left ,&lh);
38- isRight=isBalancedUtil (root->right ,&rh);
39- *height=(lh>rh?lh:rh)+1 ;
40- if (abs (lh-rh)>1 )
41- return 0 ;
42- return isLeft&&isRight;
36+ int lh=0 , rh=0 ;
37+ bool isLeft = isBalancedUtil (root->left , lh);
38+ bool isRight = isBalancedUtil (root->right , rh);
39+ height = (lh > rh ? lh : rh) + 1 ;
40+ return (abs (lh-rh)<=1 && isLeft && isRight);
41+ }
42+
43+ };
44+
45+ // Notes:
46+ // I think the above solution should be more efficent than the below,
47+ // but for leetcode, the below solution needs 60ms, the above needs 88ms
48+ class Solution {
49+ public:
50+ bool isBalanced (TreeNode *root) {
51+ if (root==NULL ) return true ;
52+
53+ int left = treeDepth (root->left );
54+ int right = treeDepth (root->right );
55+
56+ if (left-right>1 || left-right < -1 ) {
57+ return false ;
58+ }
59+ return isBalanced (root->left ) && isBalanced (root->right );
60+ }
61+
62+ int treeDepth (TreeNode *root) {
63+ if (root==NULL ){
64+ return 0 ;
65+ }
66+
67+ int left=1 , right=1 ;
68+
69+ left += treeDepth (root->left );
70+ right += treeDepth (root->right );
71+
72+ return left>right?left:right;
4373 }
4474
4575};
0 commit comments