-
-
Notifications
You must be signed in to change notification settings - Fork 298
/
Copy path98.cpp
84 lines (80 loc) · 2.1 KB
/
98.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
__________________________________________________________________________________________________
12ms
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
Solution(){
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
}
void inorderTraverse(TreeNode* root, long long& prev_val, bool& bad)
{
if (root == nullptr or bad)
{
return;
}
inorderTraverse(root->left, prev_val, bad);
if (prev_val >= root->val)
{
bad = true;
return;
}
prev_val = root->val;
inorderTraverse(root->right, prev_val, bad);
}
bool isValidBST(TreeNode* root)
{
bool bad = false;
long long prev_val = LLONG_MIN;
inorderTraverse(root, prev_val, bad);
return not bad;
}
};
__________________________________________________________________________________________________
11320 kb
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode * findRight(TreeNode* root){
while(root->right!=NULL){root=root->right;}
return root;
}
bool isValidBST(TreeNode* root) {
// if(!root){return true;}
// if(root->left==NULL && root->right==NULL){return true;}
stack<int> s;
while(root!=NULL){
if(root->left==NULL){
if(!s.empty() && s.top()>=root->val){return false;}
if(!s.empty()){s.pop();}
s.push(root->val);
root=root->right;
}else{
TreeNode * t=root->left;
TreeNode * temp=findRight(root->left);
temp->right=root;
temp->right->left=NULL;
root=t;
}
}
return true;
}
};
__________________________________________________________________________________________________