-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbalanced-binary-tree.cpp
41 lines (39 loc) · 1.04 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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
map<TreeNode*, int> h;
int getHeight (TreeNode *node) {
if (node == NULL){
return h[node] = -1;
}
if (node->left == NULL && node->right == NULL){
return 0;
}
if (h.count(node) > 0){
return h[node];
}
return h[node] = 1 + max(getHeight(node->left), getHeight(node->right));
}
bool isBalanced(TreeNode *root) {
getHeight(root);
if (root == NULL){
return -1;
}
if (root->left == NULL && root->right == NULL){
return true;
}
return
isBalanced(root->left) &&
isBalanced(root->right) &&
h[root->left] - h[root->right] >= -1 &&
h[root->left] - h[root->right] <= 1;
}
};