forked from xperzy/careerup150
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4-1.cpp
64 lines (49 loc) · 1.07 KB
/
4-1.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
62
63
64
#include <iostream>
#include <math.h>
using namespace std;
class TreeNode{
public:
TreeNode* left;
TreeNode* right;
int val;
TreeNode(int i):val(i),left(NULL),right(NULL){}
};
int getH(TreeNode* root){
if (root==NULL){
return 0;
}else{
int l = getH(root->left);
if (l==-1){return -1;}
int r = getH(root->right);
if (r==-1){return -1;}
if (abs(r-l)>1){
return -1;
}else{
return max(l,r)+1;
}
}
}
bool isBalanced(TreeNode* root){
if (getH(root)==-1){
return false;
}else{
return true;
}
}
int main(){
TreeNode* root = new TreeNode(0);
root->left = new TreeNode(1);
root->right = new TreeNode(2);
root->left->left = new TreeNode(3);
root->left->right = new TreeNode(4);
root->right->left = new TreeNode(5);
root->right->right = new TreeNode(6);
root->right->right->right = new TreeNode(7);
root->right->right->right->right = new TreeNode(8);
if (isBalanced(root)){
cout << "Balanced!"<< endl;
}else{
cout << "unBalanced!" << endl;
}
return 0;
}