|
11 | 11 | */
|
12 | 12 | class Solution {
|
13 | 13 | 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) { |
17 | 16 | if(!root) return true;
|
18 | 17 |
|
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 | + } |
20 | 21 |
|
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); |
22 | 23 | }
|
23 | 24 |
|
24 | 25 | 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; |
27 | 74 | }
|
| 75 | + |
28 | 76 | };
|
0 commit comments