forked from zhuli19901106/leetcode-zhuli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbalanced-binary-tree_1_AC.cpp
56 lines (50 loc) · 1.32 KB
/
balanced-binary-tree_1_AC.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
// Cache the result.
#include <algorithm>
#include <unordered_map>
using std::max;
using std::min;
using std::unordered_map;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
Solution() {
height[NULL] = 0;
balanced[NULL] = true;
}
bool isBalanced(TreeNode* root) {
if (balanced.find(root) != balanced.end()) {
return balanced[root];
}
int hl = getHeight(root->left);
int hr = getHeight(root->right);
if (max(hl, hr) - min(hl, hr) > 1) {
return balanced[root] = false;
}
if (!isBalanced(root->left) || !isBalanced(root->right)) {
return balanced[root] = false;
}
return balanced[root] = true;
}
~Solution() {
height.clear();
balanced.clear();
}
private:
unordered_map<TreeNode*, int> height;
unordered_map<TreeNode*, bool> balanced;
int getHeight(TreeNode* root) {
if (height.find(root) != height.end()) {
return height[root];
}
return height[root] = 1 + max(getHeight(root->left),
getHeight(root->right));
}
};