-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathLeetCode#106.cc
60 lines (60 loc) · 1.65 KB
/
LeetCode#106.cc
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
55
56
57
58
59
60
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
bool dfs(TreeNode* root, int& pre, bool& flag){
if(root==NULL) return true;
if(root->left==NULL && root->right==NULL){
if(flag==false || root->val > pre){
pre = root->val;
flag = true;
return true;
}
else return false;
}
else if(root->left==NULL){
if(flag==false || root->val > pre){
flag = true;
pre = root->val;
}
else return false;
return dfs(root->right,pre,flag);
}
else if(root->right==NULL){
bool r = dfs(root->left,pre,flag);
if(r==false) return false;
if(flag==false || root->val > pre){
flag = true;
pre = root->val;
return true;
}
else return false;
}
else{
bool r = dfs(root->left,pre,flag);
if(r==false) return false;
if(flag==false || root->val > pre){
flag = true;
pre = root->val;
}
else return false;
return dfs(root->right,pre,flag);
}
}
public:
bool isValidBST(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(root==NULL) return true;
bool flag = false;
int pre = -1;
return dfs(root,pre,flag);
}
};