Skip to content

Commit 7268885

Browse files
committed
Merge branch 'patch-1' of https://github.com/FreeJoker/leetcode-1 into FreeJoker-patch
2 parents 5217f8e + 81135fa commit 7268885

File tree

1 file changed

+15
-21
lines changed

1 file changed

+15
-21
lines changed

src/balancedBinaryTree/balancedBinaryTree.cpp

Lines changed: 15 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -24,28 +24,22 @@
2424
class Solution {
2525
public:
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
};

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy