99. Recover Binary Search Tree

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?

解法1: In-order Traversal O(N)

BST的很重要的性质就是对他进行in order traversal的话,得到的是一个有序数组。
那么可以按照in order traversal,找到第一个node使得node.val >= node.successor.val和最后一个node使得node.predecessor.val >= node.val就可以了

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
TreeNode first = null;
TreeNode second = null;
TreeNode prev = null;
public void recoverTree(TreeNode root) {
if (root == null) return;
inOrder(root);
if (first == null || second == null) return;
int temp = first.val;
first.val = second.val;
second.val = temp;
return;
}
private void inOrder(TreeNode root) {
if (root == null) return;
inOrder(root.left);
if (prev != null && prev.val >= root.val) {
if (first == null) {
first = prev;
}
if (first != null) {
second = root;
}
}
prev = root;
inOrder(root.right);
}
}