forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution3.java
58 lines (49 loc) · 1.34 KB
/
Solution3.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-05-29
/// Using Morris inOrder traversal
/// Find the mistaked swapped nodes during the traversing
///
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution3 {
private TreeNode pre;
private TreeNode a, b;
public void recoverTree(TreeNode root) {
TreeNode cur = root;
while(cur != null){
if(cur.left == null){
process(cur);
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;
process(cur);
cur = cur.right;
}
}
}
int t = a.val;
a.val = b.val;
b.val = t;
}
private void process(TreeNode node){
if(pre != null && pre.val > node.val){
if(a == null){
a = pre;
b = node;
}
else
b = node;
}
pre = node;
}
}