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?
思路:看到BST,就应该想到BST的特点,就是中序遍历一颗BST,得到是一个升序的排列,如果BST中有两个结点交换了,那么中序遍历该BST得到的排列中会有存在两次降序,也可能只有一次(当相邻的两个结点交换时),可以先将BST进行中序遍历,将结果存在集合中,然后遍历集合找出交换的两个结点,然后将两个结点的值交换即可。这样需要o(n)的空间复杂度。
其实在中序遍历的过程中,就可以记录当前结点的前一个结点,比较前一个结点的值和当前结点的值,前一个结点比当前结点大的时候就找到了被交换了结点。
public class Solution {
private TreeNode pre=null;
private TreeNode m1=null;
private TreeNode m2=null;
public void recoverTree(TreeNode root) {
inOrderTraversal(root);
if(m1!=null && m2!=null)
{
int temp=m1.val;
m1.val=m2.val;
m2.val=temp;
}
}
public void inOrderTraversal(TreeNode root)
{
if(root==null) return;
inOrderTraversal(root.left);
if(pre!=null && pre.val > root.val)
{
if(m1==null){
m1=pre;
m2=root;
}else m2=root;
}
pre=root;
inOrderTraversal(root.right);
}
}