-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBST2NodeSwap.java
More file actions
47 lines (42 loc) · 1.24 KB
/
Copy pathBST2NodeSwap.java
File metadata and controls
47 lines (42 loc) · 1.24 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
import java.util.Arrays;
public class BST2NodeSwap {
int[] inorder = new int[1001];
int bindex = 0;
public void recoverTree(TreeNode root) {
if (root == null || isLeafNode(root)) return;
int len = inOrder(root, -1);
Arrays.sort(inorder, 0, len+1);
correctBST(root);
}
private void correctBST(TreeNode root) {
if(root == null) return;
if (isLeafNode(root)) {
if (root.val != inorder[bindex]) {
root.val = inorder[bindex];
}
bindex++;
return;
}
correctBST(root.left);
if (root.val != inorder[bindex]) {
root.val = inorder[bindex];
}
bindex++;
correctBST(root.right);
}
private int inOrder(TreeNode root, int index) {
System.out.println(inorder);
if (root == null) return index;
if (isLeafNode(root)) {
inorder[++index] = root.val;
return index;
}
index = inOrder(root.left, index);
inorder[++index] = root.val;
index = inOrder(root.right, index);
return index;
}
private boolean isLeafNode(TreeNode root) {
return root.left == null && root.right == null;
}
}