-
Notifications
You must be signed in to change notification settings - Fork 118
/
98.c
126 lines (110 loc) · 3.12 KB
/
98.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
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
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
int minValue(struct TreeNode *root) {
int l, r;
if (root->left == NULL && root->right == NULL) {
return root->val;
}
else if (root->left && root->right == NULL) {
l = minValue(root->left);
return l < root->val ? l : root->val;
}
else if (root->right && root->left == NULL) {
r = minValue(root->right);
return r < root->val ? r : root->val;
}
else {
l = minValue(root->left);
r = minValue(root->right);
return l < r ? l : r;
}
}
int maxValue(struct TreeNode *root) {
int l, r;
if (root->left == NULL && root->right == NULL) {
return root->val;
}
else if (root->left && root->right == NULL) {
l = maxValue(root->left);
return l > root->val ? l : root->val;
}
else if (root->right && root->left == NULL) {
r = maxValue(root->right);
return r > root->val ? r : root->val;
}
else {
l = maxValue(root->left);
r = maxValue(root->right);
return l > r ? l : r;
}
}
bool isValidBST(struct TreeNode *root) {
if (root == NULL)
return true;
if (root->left == NULL && root->right == NULL) {
return true;
}
else if (root->left && root->right == NULL) {
if (root->left->val < root->val
&& maxValue(root->left) < root->val
&& isValidBST(root->left))
return true;
else return false;
}
else if (root->right && root->left == NULL) {
if (root->right->val > root->val
&& minValue(root->right) > root->val
&& isValidBST(root->right))
return true;
else return false;
}
else {
if (root->left->val < root->val
&& root->right->val > root->val
&& maxValue(root->left) < root->val
&& minValue(root->right) > root->val
&& isValidBST(root->left)
&& isValidBST(root->right)) {
return true;
}
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(6, sizeof(struct TreeNode));
struct TreeNode *p = t;
p->val = 4;
p->left = ++t;
t->val = 2;
p->left->left = ++t;
t->val = 1;
t->left = t->right = NULL;
p->left->right = ++t;
t->val = 3;
t->left = t->right = NULL;
p->right = ++t;
t->val = 5;
t->left = t->right = NULL;
printTreePreOrder(p); printf("\n");
printf("%d\n", isValidBST(p)); /* should be true*/
p->right->left = ++t;
t->val = 2;
t->left = t->right = NULL;
printTreePreOrder(p); printf("\n");
printf("%d\n", isValidBST(p)); /* should be false*/
return 0;
}