-
Notifications
You must be signed in to change notification settings - Fork 0
/
isValidBST.cpp
54 lines (53 loc) · 1.41 KB
/
isValidBST.cpp
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
43
44
45
46
47
48
49
50
51
52
53
54
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int max,min;
if(!root)
return true;
return isBST(root,max,min);
}
bool isBST(TreeNode *root,int &max,int &min) {
if(!root)
return true;
if(!root->left && !root->right) {
max = root->val;
min = root->val;
return true;
}
int l_max,l_min,r_max,r_min;
if(isBST(root->left,l_max,l_min) && isBST(root->right,r_max,r_min)) {
if(!root->left) {
if(root->val < r_min) {
min = root->val;
max = r_max;
return true;
}
}
else if(!root->right) {
if(root->val > l_max) {
min = l_min;
max = root->val;
return true;
}
}
else if(root->val > l_max && root->val < r_min) {
min = l_min;
max = r_max;
return true;
}
return false;
}
return false;
}
};