File tree Expand file tree Collapse file tree 1 file changed +15
-21
lines changed Expand file tree Collapse file tree 1 file changed +15
-21
lines changed Original file line number Diff line number Diff line change 2424class Solution {
2525public:
2626 bool isBalanced (TreeNode *root) {
27- if (root==NULL ) return true ;
28-
29- int left = treeDepth (root->left );
30- int right = treeDepth (root->right );
31-
32- if (left-right>1 || left-right < -1 ) {
33- return false ;
34- }
35- return isBalanced (root->left ) && isBalanced (root->right );
27+ int height=0 ;
28+ return isBalancedUtil (root,&height);
3629 }
37-
38- int treeDepth (TreeNode *root) {
39- if (root==NULL ){
40- return 0 ;
41- }
42-
43- int left=1 , right=1 ;
44-
45- left += treeDepth (root->left );
46- right += treeDepth (root->right );
47-
48- return left>right?left:right;
30+ bool isBalancedUtil (TreeNode* root,int *height){
31+ if (root==NULL ){
32+ *height=0 ;
33+ return 1 ;
34+ }
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;
4943 }
5044
5145};
You can’t perform that action at this time.
0 commit comments