forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution2.java
46 lines (36 loc) · 914 Bytes
/
Solution2.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
/// Source : https://leetcode.com/problems/validate-binary-search-tree/description/
/// Author : liuyubobobo
/// Time : 2018-05-22
/// Using inOrder traverse
/// Find the mistaked swapped nodes during the traversing
///
/// Time Complexity: O(n)
/// Space Complexity: O(h)
class Solution2 {
private TreeNode pre;
private TreeNode a, b;
public void recoverTree(TreeNode root) {
pre = null;
a = null;
b = null;
inOrder(root);
int t = a.val;
a.val = b.val;
b.val = t;
}
private void inOrder(TreeNode node){
if(node == null)
return;
inOrder(node.left);
if(pre != null && pre.val > node.val){
if (a == null){
a = pre;
b = node;
}
else
b = node;
}
pre = node;
inOrder(node.right);
}
}