keep moving

# 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?

public class Solution {
TreeNode mistake1, mistake2;;
TreeNode pre;

void recursive_traversal(TreeNode root) {
if(root==null) {
return;
}
if(root.left!=null) {
recursive_traversal(root.left);
}
if(pre!=null&&root.val<pre.val) {
if(mistake1==null) {
mistake1 = pre;
mistake2 = root;
} else {
mistake2 = root;
}
}
//得到下一个root的pre节点
pre = root;
if(root.right!=null) {
recursive_traversal(root.right);
}
}
public void recoverTree(TreeNode root) {
//pre必须设为null，通过遍历的时候设进去。因为是中序遍历，所以pre应该是深层叶子左子树的父节点。
recursive_traversal(root);
if(mistake1!=null&&mistake2!=null) {
int tmp = mistake1.val;
mistake1.val = mistake2.val;
mistake2.val = tmp;
}
}
}

#### LeetCode99—Recover Binary Search Tree

2016-03-19 22:12:41

#### LeetCode 99:Recover Binary Search Tree

2015-12-28 15:37:36

#### Recover Binary Search Tree -- LeetCode

2014-04-27 03:09:51

#### 【LeetCode】Recover Binary Search Tree 解题报告

2015-03-21 11:58:37

#### leetcode 99 Recover Binary Search Tree (python)

2016-07-25 23:37:11

#### Recover Binary Search Tree（恢复二叉搜索树）

2014-03-07 21:42:01

#### Recover Binary Search Tree(BST中序遍历)

2015-05-27 16:21:46

#### Recover Binary Search Tree BST找乱序的两个元素 @LeetCode

2013-11-22 04:32:00

#### (leetcode 99) Recover Binary Search Tree

2016-02-01 15:49:25

#### Leetcode 99. Recover Binary Search Tree 恢复二叉搜索树 解题报告

2016-09-01 15:54:39