Balanced Binary Tree LeetCode solution in C++

1
class Solution {
2
public:
3
bool isBalanced(TreeNode *root) {
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
11
// recursion...
12
int Height(TreeNode *root) {
13
// Base case...
14
if (root == NULL) return 0;
15
// Height of left subtree...
16
int leftHeight = Height(root->left);
17
// Height of height subtree...
18
int rightHight = Height(root->right);
19
// In case of left subtree or right subtree unbalanced or their heights
20
// differ by more than ‘1’, return -1...
21
if (leftHeight == -1 || rightHight == -1 || abs(leftHeight - rightHight) > 1) return -1;
22
// Otherwise, return the height of this subtree as max(leftHeight,
23
// rightHight) + 1...
24
return max(leftHeight, rightHight) + 1;
25
}
26
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0