-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathvalidate-binary-search-tree.cc
More file actions
46 lines (40 loc) · 938 Bytes
/
validate-binary-search-tree.cc
File metadata and controls
46 lines (40 loc) · 938 Bytes
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
// Validate Binary Search Tree
class Solution {
public:
bool isValidBST(TreeNode *x) {
TreeNode *y = NULL;
stack<TreeNode *> s;
for(;;) {
for (; x; x = x->left)
s.push(x);
if (s.empty())
return true;
x = s.top();
s.pop();
if (y && x->val <= y->val)
return false;
y = x;
x = x->right;
}
}
};
///
class Solution {
public:
bool isValidBST(TreeNode *root) {
return f(root, NULL, NULL);
}
bool f(TreeNode *x, TreeNode *l, TreeNode *h) {
return !x || (!l || l->val < x->val) && (!h || x->val < h->val) && f(x->left, l, x) && f(x->right, x, h);
}
};
/// correct only if (LONG_MIN, LONG_MAX)
class Solution {
public:
bool isValidBST(TreeNode *root) {
return f(root, LONG_MIN, LONG_MAX);
}
bool f(TreeNode *x, long l, long h) {
return !x || l < x->val && x->val < h && f(x->left, l, x->val) && f(x->right, x->val, h);
}
};