-
Notifications
You must be signed in to change notification settings - Fork 0
/
98_validBST.cpp
92 lines (65 loc) · 1.79 KB
/
98_validBST.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
#include <iostream>
#include <stack>
using namespace std;
struct TreeNode
{
TreeNode *left;
TreeNode *right;
int val;
TreeNode(int arg) : left(NULL), right(NULL), val(arg) {}
};
TreeNode *pre = NULL;
bool helper(TreeNode *root, TreeNode *min, TreeNode *max)
{
if (NULL == root) return true;
if (min && min->val >= root->val) return false;
if (max && max->val <= root->val) return false;
return helper(root->left, min, root) && helper(root->right, root, max);
}
bool isValidBST(TreeNode *root)
{
// ordered array
// stack<int> *container = new stack<int>();
// insertElement(root, container);
// if (2 > container->size()) return true;
// int tmp = container->top();
// container->pop();
// while (0 != container->size()) {
// if (tmp > container->top()) {
// return false;
// }
// tmp = container->top();
// container->pop();
// }
// recursive
if (NULL == root) return true;
if (!isValidBST(root->left)) return false;
if (pre && pre->val >= root->val) return false;
pre = root;
if (!isValidBST(root->right)) return false;
// return true;
// return helper(root, NULL, NULL);
return true;
}
void showTree(TreeNode *root) {
if (root) {
showTree(root->left);
std::cout << root->val;
showTree(root->right);
}
}
int
main(int argc, char const *argv[])
{
TreeNode *root = new TreeNode(4);
root->left = new TreeNode(2);
root->left->left = new TreeNode(1);
root->left->right = new TreeNode(3);
root->right = new TreeNode(6);
root->right->left = new TreeNode(5);
root->right->right = new TreeNode(7);
showTree(root);
std::cout << std::endl;
cout << isValidBST(root) << endl;
return 0;
}