forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution5.java
58 lines (48 loc) · 1.4 KB
/
Solution5.java
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
/// Source : https://leetcode.com/problems/validate-binary-search-tree/description/
/// Author : liuyubobobo
/// Time : 2018-12-16
/// 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)
public class Solution5 {
private boolean flag;
private int pre;
public boolean isValidBST(TreeNode root) {
flag = false;
pre = -1;
TreeNode cur = root;
boolean res = true;
while(cur != null){
if(cur.left == null){
if(!process(cur.val)) return 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.val))
return false;
cur = cur.right;
}
}
}
return true;
}
private boolean process(int v){
if(flag && pre >= v)
return false;
flag = true;
pre = v;
return true;
}
}