-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path110.balanced_binary_tree.cpp
61 lines (48 loc) · 1006 Bytes
/
110.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
57
58
59
60
61
#include "include/header/tree.hpp"
using namespace std;
class Solution
{
private:
bool result = true;
public:
bool isBalanced(TreeNode *root)
{
helper(root);
return this->result;
}
int helper(TreeNode *root)
{
if (!result)
{
return -1;
}
if (!root)
{
return 0;
}
int l = 0, r = 0;
if (root->left)
{
l = helper(root->left);
}
if (root->right)
{
r = helper(root->right);
}
if (abs(r - l) > 1)
{
this->result = false;
}
return max(r, l) + 1;
}
};
int main()
{
Solution s;
vector<int> v1 = {3, 9, 20, INT_MAX, INT_MAX, 15, 7};
auto t1 = TreeNode::deserialize(v1);
assert(s.isBalanced(t1) == true);
vector<int> v2 = {1, 2, 2, 3, 3, INT_MAX, INT_MAX, 4, 4};
auto t2 = TreeNode::deserialize(v2);
assert(s.isBalanced(t2) == false);
}