forked from mengli/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecover Binary Search Tree.java
More file actions
51 lines (46 loc) · 1.35 KB
/
Recover Binary Search Tree.java
File metadata and controls
51 lines (46 loc) · 1.35 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
Recover Binary Search TreeSep 1 '12
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Note:
A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public void recoverTree(TreeNode root) {
if (root == null) return;
ArrayList<TreeNode> nodes = new ArrayList<TreeNode>();
findWrongNode(root, nodes);
TreeNode a = null, b = null;
int i = 0;
for (i = 0; i < nodes.size() - 1; i++) {
if (nodes.get(i).val > nodes.get(i + 1).val) {
a = nodes.get(i);
break;
}
}
for (int j = i + 1; j < nodes.size() - 1; j++) {
if (nodes.get(j).val > nodes.get(j + 1).val) {
b = nodes.get(j + 1);
break;
}
}
if (b == null)
b = nodes.get(i + 1);
int t = a.val;
a.val = b.val;
b.val = t;
}
private void findWrongNode(TreeNode root, ArrayList<TreeNode> nodes) {
if (root == null) return;
findWrongNode(root.left, nodes);
nodes.add(root);
findWrongNode(root.right, nodes);
}
}