forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain5.cpp
More file actions
93 lines (73 loc) · 1.97 KB
/
main5.cpp
File metadata and controls
93 lines (73 loc) · 1.97 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
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
85
86
87
88
89
90
91
92
93
/// Source : https://leetcode.com/problems/validate-binary-search-tree/description/
/// Author : liuyubobobo
/// Time : 2018-05-28
#include <iostream>
using namespace std;
/// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
/// Morris InOrder traversal
/// Attention: you can not change the give Tree structure in Leetcode,
/// So try to return result early will lead to RE :-)
///
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution {
private:
bool flag;
int pre;
public:
bool isValidBST(TreeNode* root) {
flag = false;
pre = -1;
TreeNode* cur = root;
bool res = true;
while(cur != NULL){
if(cur->left == NULL){
if(!process(cur))
res = false;
cur = cur->right;
}
else{
TreeNode* prev = cur->left;
while(prev->right != NULL && prev->right != cur)
prev = prev->right;
if(prev->right == NULL){
prev->right = cur;
cur = cur->left;
}
else{
prev->right = NULL;
if(!process(cur))
res = false;
cur = cur->right;
}
}
}
return res;
}
private:
bool process(TreeNode* node){
if(flag && pre >= node->val)
return false;
flag = true;
pre = node->val;
return true;
}
};
void print_bool(bool res){
cout << (res ? "True" : "False") << endl;
}
int main() {
TreeNode* root = new TreeNode(5);
root->left = new TreeNode(1);
root->right = new TreeNode(4);
root->right->left = new TreeNode(3);
root->right->right = new TreeNode(6);
print_bool(Solution().isValidBST(root));
return 0;
}