-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathis_valid_bst.cpp
76 lines (60 loc) · 2.03 KB
/
is_valid_bst.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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
//using range min and max
bool helper(TreeNode *root, long min, long max) {
if(!root) return true;
if(root->val <= min or root->val >= max) {
return false;
}
return helper(root->left, min, root->val) and helper(root->right, root->val, max);
}
bool isValidBST(TreeNode* root) {
if(!root) return true;
return helper(root, LONG_MIN, LONG_MAX);
}
//using prev node recursive
TreeNode *prev;
bool isValidBST(TreeNode* root) {
if(!root) return true;
if(!isValidBST(root->left))
return false;
//the prev node here keeps track of the prev node to the current node.
//we are doing inorder traversal (LVR). Always, the last-seen node must be smaller than the current node.
if(prev != NULL and prev->val >= root->val)
return false;
prev = root;
if(!isValidBST(root->right))
return false;
return true;
}
//iterative
bool isValidBST(TreeNode *root) {
TreeNode *current = root, *prev = NULL;
stack<TreeNode *> st;
while(!st.empty() or current) {
if(current) {
st.push(current);
current = current->left;
}
else {
auto parent = st.top();
st.pop();
if(prev and parent->val <= prev->val) return false;
prev = parent;
current = parent->right;
}
}
return true;
}
};