Skip to content

Commit b68b7b6

Browse files
Create is_valid_bst.cpp
1 parent 2d791a6 commit b68b7b6

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

is_valid_bst.cpp

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution {
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) {
17+
if(!root) return true;
18+
19+
if(min and root->val <= min->val || max and root->val >= max->val) return false;
20+
21+
return isValidBSTHelper(root->left, min, root) and isValidBSTHelper(root->right, root, max);
22+
}
23+
24+
bool isValidBST(TreeNode* root) {
25+
// if(!root) return true;
26+
return isValidBSTHelper(root, NULL, NULL);
27+
}
28+
};

0 commit comments

Comments
 (0)