-
Notifications
You must be signed in to change notification settings - Fork 28
/
Balanced_Binary_Tree.cpp
56 lines (52 loc) · 1.38 KB
/
Balanced_Binary_Tree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// O(n^2) (Accepted)
class Solution {
public:
int maxDepth(TreeNode * root) {
if (!root) return 0;
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
bool isBalanced(TreeNode *root) {
if (!root) return true;
if (abs(maxDepth(root->left) - maxDepth(root->right)) > 1) return false;
return (isBalanced(root->left) and isBalanced(root->right));
}
};
// O(n) time and O(Height) space (Accepted)
class Solution {
public:
int checkHeight(TreeNode *root) {
if(!root) {
return 0;
}
int leftHeight = checkHeight(root->left);
if(leftHeight == -1) {
return -1;
}
int rightHeight = checkHeight(root->right);
if(rightHeight == -1) {
return -1;
}
int diff = abs(leftHeight - rightHeight);
if(diff > 1) {
return -1;
} else {
return max(leftHeight, rightHeight) + 1;
}
}
bool isBalanced(TreeNode *root) {
if(checkHeight(root) != -1) {
return true;
} else {
return false;
}
}
};