-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy path110.c
80 lines (69 loc) · 1.87 KB
/
110.c
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
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
int maxDepth(struct TreeNode *root) {
if (root == NULL)
return 0;
int l = maxDepth(root->left);
int r = maxDepth(root->right);
if (l > r)
return l + 1;
else
return r + 1;
}
bool isBalanced(struct TreeNode *root) {
if (root == NULL)
return true;
int l = maxDepth(root->left);
int r = maxDepth(root->right);
int d = l - r;
if (d == 0 || d == 1 || d == -1) {
if (isBalanced(root->left) && isBalanced(root->right)) {
return true;
}
else return false;
}
else return false;
}
void printTreePreOrder(struct TreeNode *p) {
if (p != NULL) {
printf("%d", p->val);
printTreePreOrder(p->left);
printTreePreOrder(p->right);
}
else printf("#");
}
int main() {
struct TreeNode *t = (struct TreeNode *)calloc(7, sizeof(struct TreeNode));
struct TreeNode *p = t;
p->val = 1;
p->left = ++t;
t->val = 2;
p->left->left = ++t;
p->left->right = NULL;
t->val = 3;
p->left->left->left = ++t;
p->left->left->right = NULL;
t->val = 4;
t->left = t->right = NULL;
p->right = ++t;
t->val = 2;
p->right->left = NULL;
p->right->right = ++t;
t->val = 3;
p->right->right->left = NULL;
p->right->right->right = ++t;
t->val = 4;
t->left = t->right = NULL;
printTreePreOrder(p); printf("\n");
printf("%d\n", isBalanced(p)); /* should be false */
printf("%d\n", isBalanced(p->left)); /* should be false */
printf("%d\n", isBalanced(p->left->left)); /* should be true */
printf("%d\n", isBalanced(NULL)); /* should be true */
return 0;
}