# LeetCode 重构二叉搜索数，即找出两个被交换的节点

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?

confused what"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.

OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1
/ \
2   3
/
4
\
5

The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}".

“直观的想法可能是中序遍历一遍二叉树，得到一个有序的二叉树，然后找出其中逆序的地方，交换回来就好了。但这样空间复杂度就是O(n)，题目要求O(1)。

import java.util.*;
/**
* Definition for binary tree*/
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x;
}
}
class Solution {
private TreeNode pre=null;
private TreeNode mistake1,mistake2=null;
public void recoverTree(TreeNode root) {
inOrderTraversal(root);
int temp=mistake2.val;
mistake2.val=mistake1.val;
mistake1.val=temp;
}
/*中序遍历查找出错的两个节点,只有两个节点出错哦
* 左节点值<根节点值<右节点值
* 首先从左子树遍历到底
* */
public void inOrderTraversal(TreeNode root){
if(root==null)
return;
//中序遍历
inOrderTraversal(root.left);//左子树遍历到底
if(pre!=null&&pre.val>root.val){
if(mistake1==null)
mistake1=pre;
mistake2=root;
}
pre=root;//最底下的左节点
inOrderTraversal(root.right);
}