Skip to content

Commit 7beed39

Browse files
authored
98. Validate Binary Search Tree
1 parent 5c9fb83 commit 7beed39

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

validateBinarySearchTree.cpp

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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+
bool isValidBST(TreeNode* root){
15+
stack <TreeNode*> st;
16+
TreeNode* prev = NULL;
17+
18+
while (root || !st.empty()){
19+
while (root){
20+
st.push(root);
21+
root = root->left;
22+
}
23+
root = st.top();
24+
st.pop();
25+
26+
if(prev && root->val<=prev->val){
27+
return false;
28+
}
29+
30+
prev = root;
31+
root = root->right;
32+
}
33+
return true;
34+
}
35+
};
36+
37+
38+
39+
/**
40+
* Definition for a binary tree node.
41+
* struct TreeNode {
42+
* int val;
43+
* TreeNode *left;
44+
* TreeNode *right;
45+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
46+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
47+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
48+
* };
49+
*/
50+
class Solution {
51+
public:
52+
bool isValidBST(TreeNode* root){
53+
return isValidBSTHelper(root, LLONG_MIN, LLONG_MAX);
54+
}
55+
bool isValidBSTHelper(TreeNode* root, long min, long max){
56+
if (root == NULL) return true;
57+
if (root->val<=min || root->val>=max) return false;
58+
return isValidBSTHelper(root->left, min, root->val) && isValidBSTHelper(root->right, root->val, max);
59+
}
60+
};

0 commit comments

Comments
 (0)