/
recoverTree2.java
57 lines (52 loc) · 1.26 KB
/
recoverTree2.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
/*
* Leetcode 99: Recover Binary Search Tree
* https://leetcode.com/problems/recover-binary-search-tree/
* Method with O(log n) space
* Martin.Xia
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
TreeNode pre;
TreeNode first;
TreeNode second;
private void inorder(TreeNode root){
if(root == null)
return;
inorder(root.left);
if(pre == null){
pre = root;
}else{
if(pre.val > root.val){
if(first == null){
first = pre;
}
second = root;
}
pre = root;
}
inorder(root.right);
}
private void swap(TreeNode first, TreeNode second) {
if(first!=null && second!=null){
int temp = first.val;
first.val = second.val;
second.val = temp;
}
return;
}
public void recoverTree(TreeNode root) {
pre = null;
first = null;
second = null;
inorder(root);
swap(first,second);
}
}