File tree Expand file tree Collapse file tree 1 file changed +25
-1
lines changed Expand file tree Collapse file tree 1 file changed +25
-1
lines changed Original file line number Diff line number Diff line change 2222 * };
2323 */
2424class Solution {
25+ public:
26+ bool isBalanced (TreeNode *root) {
27+ int height=0 ;
28+ return isBalancedUtil (root, height);
29+ }
30+
31+ bool isBalancedUtil (TreeNode* root, int & height){
32+ if (root==NULL ){
33+ height=0 ;
34+ return true ;
35+ }
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 {
2549public:
2650 bool isBalanced (TreeNode *root) {
2751 if (root==NULL ) return true ;
@@ -39,7 +63,7 @@ class Solution {
3963 if (root==NULL ){
4064 return 0 ;
4165 }
42-
66+
4367 int left=1 , right=1 ;
4468
4569 left += treeDepth (root->left );
You can’t perform that action at this time.
0 commit comments