1
- // Runtime: 8 ms (Top 96.99%) | Memory: 20.9 MB (Top 54.47%)
2
1
class Solution {
3
2
public:
4
3
bool isBalanced (TreeNode* root) {
5
- return height (root) != -1 ;
6
- }
7
- int height (TreeNode* root){
8
- if (!root)
9
- return 1 ;
10
-
11
- int left = height (root->left );
12
-
13
- if (left == -1 )
14
- return -1 ;
15
-
16
- int right = height (root->right );
17
-
18
- if (right == -1 )
19
- return -1 ;
20
-
21
- if (abs (left - right) > 1 )
22
- return -1 ;
23
-
24
- return 1 + max (left, right);
4
+ // If the tree is empty, we can say it’s balanced...
5
+ if (root == NULL ) return true ;
6
+ // Height Function will return -1, when it’s an unbalanced tree...
7
+ if (Height (root) == -1 ) return false ;
8
+ return true ;
9
+ }
10
+ // Create a function to return the “height” of a current subtree using recursion...
11
+ int Height (TreeNode* root) {
12
+ // Base case...
13
+ if (root == NULL ) return 0 ;
14
+ // Height of left subtree...
15
+ int leftHeight = Height (root->left );
16
+ // Height of height subtree...
17
+ int rightHight = Height (root->right );
18
+ // In case of left subtree or right subtree unbalanced or their heights differ by more than ‘1’, return -1...
19
+ if (leftHeight == -1 || rightHight == -1 || abs (leftHeight - rightHight) > 1 ) return -1 ;
20
+ // Otherwise, return the height of this subtree as max(leftHeight, rightHight) + 1...
21
+ return max (leftHeight, rightHight) + 1 ;
25
22
}
26
23
};
0 commit comments