forked from daizhenyang/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidate Binary Search Tree.cpp
More file actions
42 lines (42 loc) · 1.08 KB
/
Validate Binary Search Tree.cpp
File metadata and controls
42 lines (42 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
pair<pair<int,int>,bool>judge(TreeNode *root)
{
int mx=root->val;
int mi=mx;
bool r=true;
pair<pair<int,int>,bool>pl,pr;
if (root->left)
{
pl=judge(root->left);
mx=max(mx,pl.first.first);
mi=min(mi,pl.first.second);
r&=pl.second;
if (pl.first.first>=root->val)r=false;
}
if (root->right)
{
pr=judge(root->right);
mx=max(mx,pr.first.first);
mi=min(mi,pr.first.second);
r&=pr.second;
if (pr.first.second<=root->val)r=false;
}
return make_pair(make_pair(mx,mi),r);
}
bool isValidBST(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (!root)return true;
return judge(root).second;
}
};