-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path110.balanced-binary-tree.cpp
More file actions
77 lines (62 loc) · 1.65 KB
/
110.balanced-binary-tree.cpp
File metadata and controls
77 lines (62 loc) · 1.65 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include "testharness.h"
#include <unordered_map>
#include <stack>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
bool isBalanced(TreeNode *root) {
if (root == NULL) return true;
std::unordered_map<TreeNode*, int> treeHight;
treeHight[NULL] = 0;
std::stack<TreeNode*> s;
s.push({root});
while (!s.empty()) {
auto ps = s.top();
int lh = -1;
int rh = -1;
auto lt = treeHight.find(ps->left);
if (lt != treeHight.end()) {
lh = (*lt).second;
} else {
s.push({ps->left});
}
auto rt = treeHight.find(ps->right);
if (rt != treeHight.end()) {
rh = (*rt).second;
} else {
s.push({ps->right});
}
if (lh >= 0 && rh >= 0) {
if (lh > rh + 1 || rh > lh + 1) return false;
s.pop();
treeHight[ps] = (lh > rh ? lh : rh) + 1;
}
}
return true;
}
};
TEST(Solution, test) {
ASSERT_EQ(2, 1+1);
TreeNode root(1);
TreeNode n11(1);
TreeNode n12(1);
TreeNode n21(1);
TreeNode n22(1);
TreeNode n23(1);
TreeNode n24(1);
root.left = &n11;
root.right = &n12;
ASSERT_EQ(true, isBalanced(&root));
n11.left = &n21;
ASSERT_EQ(true, isBalanced(&root));
n21.left = &n22;
ASSERT_EQ(false, isBalanced(&root));
n11.right = &n23;
ASSERT_EQ(false, isBalanced(&root));
}