Skip to content

Commit a682308

Browse files
committed
Runtime 7 ms (Top 96.1%) | Memory 20.0 MB (Top 96.16%)
1 parent 621c165 commit a682308

File tree

1 file changed

+18
-21
lines changed

1 file changed

+18
-21
lines changed
Lines changed: 18 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,23 @@
1-
// Runtime: 8 ms (Top 96.99%) | Memory: 20.9 MB (Top 54.47%)
21
class Solution {
32
public:
43
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;
2522
}
2623
};

0 commit comments

Comments
 (0)