Skip to content

Commit 6d78e47

Browse files
Update is_valid_bst.cpp
1 parent 48ad2fe commit 6d78e47

File tree

1 file changed

+55
-7
lines changed

1 file changed

+55
-7
lines changed

is_valid_bst.cpp

Lines changed: 55 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,18 +11,66 @@
1111
*/
1212
class Solution {
1313
public:
14-
//as per my understanding
15-
//the minNode and maxNode during traversal must point to the parent of the current node that we are exploring
16-
bool isValidBSTHelper(TreeNode *root, TreeNode *min, TreeNode *max) {
14+
//using range min and max
15+
bool helper(TreeNode *root, long min, long max) {
1716
if(!root) return true;
1817

19-
if(min and root->val <= min->val || max and root->val >= max->val) return false;
18+
if(root->val <= min or root->val >= max) {
19+
return false;
20+
}
2021

21-
return isValidBSTHelper(root->left, min, root) and isValidBSTHelper(root->right, root, max);
22+
return helper(root->left, min, root->val) and helper(root->right, root->val, max);
2223
}
2324

2425
bool isValidBST(TreeNode* root) {
25-
// if(!root) return true;
26-
return isValidBSTHelper(root, NULL, NULL);
26+
if(!root) return true;
27+
return helper(root, LONG_MIN, LONG_MAX);
28+
29+
}
30+
31+
//using prev node recursive
32+
TreeNode *prev;
33+
bool isValidBST(TreeNode* root) {
34+
35+
if(!root) return true;
36+
37+
if(!isValidBST(root->left))
38+
return false;
39+
40+
//the prev node here keeps track of the prev node to the current node.
41+
//we are doing inorder traversal (LVR). Always, the last-seen node must be smaller than the current node.
42+
if(prev != NULL and prev->val >= root->val)
43+
return false;
44+
prev = root;
45+
46+
if(!isValidBST(root->right))
47+
return false;
48+
49+
return true;
50+
}
51+
52+
//iterative
53+
bool isValidBST(TreeNode *root) {
54+
55+
TreeNode *current = root, *prev = NULL;
56+
stack<TreeNode *> st;
57+
58+
while(!st.empty() or current) {
59+
60+
if(current) {
61+
st.push(current);
62+
current = current->left;
63+
}
64+
else {
65+
auto parent = st.top();
66+
st.pop();
67+
68+
if(prev and parent->val <= prev->val) return false;
69+
prev = parent;
70+
current = parent->right;
71+
}
72+
}
73+
return true;
2774
}
75+
2876
};

0 commit comments

Comments
 (0)