Skip to content

Commit 3828e83

Browse files
committed
Create Validate Binary Search Tree.cpp
1 parent 3d0fa22 commit 3828e83

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Validate Binary Search Tree.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* Definition for binary tree
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+
* };
9+
*/
10+
class Solution {
11+
public:
12+
pair<pair<int,int>,bool>judge(TreeNode *root)
13+
{
14+
int mx=root->val;
15+
int mi=mx;
16+
bool r=true;
17+
pair<pair<int,int>,bool>pl,pr;
18+
if (root->left)
19+
{
20+
pl=judge(root->left);
21+
mx=max(mx,pl.first.first);
22+
mi=min(mi,pl.first.second);
23+
r&=pl.second;
24+
if (pl.first.first>=root->val)r=false;
25+
}
26+
if (root->right)
27+
{
28+
pr=judge(root->right);
29+
mx=max(mx,pr.first.first);
30+
mi=min(mi,pr.first.second);
31+
r&=pr.second;
32+
if (pr.first.second<=root->val)r=false;
33+
}
34+
return make_pair(make_pair(mx,mi),r);
35+
}
36+
bool isValidBST(TreeNode *root) {
37+
// Start typing your C/C++ solution below
38+
// DO NOT write int main() function
39+
if (!root)return true;
40+
return judge(root).second;
41+
}
42+
};

0 commit comments

Comments
 (0)