forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
58 lines (46 loc) · 1.39 KB
/
Solution.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-22
import java.util.ArrayList;
/// Using inOrder traverse
/// Store all Nodes in an ArrayList and find the mistaked swapped nodes
///
/// Time Complexity: O(n)
/// Space Complexity: O(n)
class Solution {
public void recoverTree(TreeNode root) {
ArrayList<TreeNode> list = new ArrayList<>();
inOrder(root, list);
TreeNode a = null;
TreeNode b = null;
for(int i = 1 ; i < list.size() ; i ++) {
if (list.get(i - 1).val > list.get(i).val) {
if (a == null){
a = list.get(i - 1);
b = list.get(i);
}
else {
b = list.get(i);
break;
}
}
}
int t = a.val;
a.val = b.val;
b.val = t;
}
private void inOrder(TreeNode node, ArrayList<TreeNode> list){
if(node == null)
return;
inOrder(node.left, list);
list.add(node);
inOrder(node.right, list);
}
public static void main(String[] args){
TreeNode root = new TreeNode(3);
root.left = new TreeNode(1);
root.right = new TreeNode(4);
root.right.left = new TreeNode(2);
(new Solution()).recoverTree(root);
}
}