-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path110.BalancedBinaryTree.cpp
More file actions
executable file
·127 lines (108 loc) · 2.72 KB
/
110.BalancedBinaryTree.cpp
File metadata and controls
executable file
·127 lines (108 loc) · 2.72 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
/*************************************************************************
> File Name: 110.BalancedBinaryTree.cpp
> Author: hulkcao
> Mail: [email protected]
> Created Time: Sat 15 Jun 2019 04:23:52 AM UTC
************************************************************************/
#include <iostream>
#include<cmath>
using namespace std;
// 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:
typedef struct BalanceParam
{
BalanceParam(): isAvl(true), height(0) {}
bool isAvl;
int height;
} BalanceParamInfo;
bool isBalanced(TreeNode *root)
{
if (root == nullptr)
{
return true;
}
BalanceParamInfo left_tree = GetHeight(root->left, 1);
if (!left_tree.isAvl)
{
return false;
}
BalanceParamInfo right_tree = GetHeight(root->right, 1);
if (!right_tree.isAvl)
{
return false;
}
if (std::abs(left_tree.height - right_tree.height) <= 1)
{
return true;
}
else
{
return false;
}
}
private:
BalanceParamInfo GetHeight(TreeNode *head, int height)
{
if (head == nullptr)
{
BalanceParamInfo balance;
balance.height = height;
return balance;
}
BalanceParamInfo left = GetHeight(head->left, height + 1);
if (!left.isAvl)
{
BalanceParamInfo balance;
balance.isAvl = false;
return balance;
}
BalanceParamInfo right = GetHeight(head->right, height + 1);
if (!right.isAvl)
{
BalanceParamInfo balance;
balance.isAvl = false;
return balance;
}
if (std::abs(left.height - right.height) <= 1)
{
BalanceParamInfo balance;
balance.height = left.height > right.height ? left.height : right.height;
balance.isAvl = true;
return balance;
}
else
{
BalanceParamInfo balance;
balance.height = left.height > right.height ? left.height : right.height;
balance.isAvl = false;
return balance;
}
}
};
int main()
{
TreeNode *root = new TreeNode(0);
root->left = new TreeNode(0);
root->left->left = new TreeNode(0);
// root->right = new TreeNode(0);
Solution s;
bool ret = s.isBalanced(root);
if (ret)
{
cout << "balanced" << endl;
}
else
{
cout << "not balanced" << endl;
}
return 0;
}