-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path39_2_BalancedBinaryTree.cpp
95 lines (80 loc) · 1.42 KB
/
39_2_BalancedBinaryTree.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
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
#include <iostream>
#include <cstdio>
using namespace std;
#define MAX 12
struct BinaryTree
{
BinaryTree *left;
BinaryTree *right;
};
void CreateTree(BinaryTree **root, int n)
{
if (n <= 0)
return ;
BinaryTree* arr[MAX];
for (int i = 0;i < n;i ++)
{
arr[i] = new BinaryTree;
arr[i]->left = NULL;
arr[i]->right = NULL;
}
int left, right;
for (int i = 0;i < n; i++)
{
cin >> left >> right;
if (left != -1)
arr[i]->left = arr[left - 1];
if (right != -1)
arr[i]->right = arr[right - 1];
}
*root = arr[0];
}
void DeleteTree(BinaryTree **root)
{
if ((*root) == NULL)
return ;
DeleteTree(&((*root)->left));
DeleteTree(&((*root)->right));
delete *root;
}
bool IsBalanceTreePartition(BinaryTree *root, int &depth)
{
if (root == NULL)
{
depth = 0;
return true;
}
int left = 0, right = 0;
if (IsBalanceTreePartition(root->left, left) && IsBalanceTreePartition(root->right, right))
{
int diff = left - right;
if (diff <= 1 && diff >= -1)
{ depth = 1 + (left > right ? left : right);
return true;
}
}
return false;
}
bool IsBalanceTree(BinaryTree *root)
{
if(root == NULL)
return false;
int depth;
return IsBalanceTreePartition(root, depth);
}
int main(void)
{
int n;
while (cin >> n)
{
BinaryTree *root = NULL;
CreateTree(&root, n);
bool TF = IsBalanceTree(root);
if (TF)
cout << "true" << endl;
else
cout << "false" << endl;
DeleteTree(&root);
}
return 0;
}