forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRecoverBinarySearchTree.java
60 lines (54 loc) · 1.57 KB
/
RecoverBinarySearchTree.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
59
60
import java.util.Stack;
public class RecoverBinarySearchTree {
TreeNode first, second, prev;
public void recoverTree(TreeNode root) {
inorder(root);
int val = first.val;
first.val = second.val;
second.val = val;
}
// Morris遍历
private void inorder(TreeNode root) {
while (root != null) {
if (root.left == null) {
detect(root);
root = root.right;
} else {
TreeNode pre = root.left;
for ( ; pre.right != null && pre.right != root; pre = pre.right);
if (pre.right == null) {
pre.right = root;
root = root.left;
} else {
pre.right = null;
detect(root);
root = root.right;
}
}
}
}
private void inorder2(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
while (!stack.isEmpty() || root != null) {
if (root != null) {
stack.push(root);
root = root.left;
} else {
root = stack.pop();
detect(root);
root = root.right;
}
}
}
private void detect(TreeNode node) {
if (prev != null) {
if (first == null && prev.val > node.val) {
first = prev;
}
if (first != null && prev.val > node.val) {
second = node;
}
}
prev = node;
}
}