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?
分析: 二叉搜索树的中序遍历是一个从小到大的序列. 若2个数换了,则需要找到这2个数的位置,第一个数满足的条件是大于其后面的一个数,第二个数的条件是其值小于前面的数.找到这2个点之后,交换值即可.
利用中序遍历来查找.
<span style="font-size:14px;">/**
* 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=new TreeNode(Integer.MIN_VALUE);
TreeNode first,second;
public void recoverTree(TreeNode root) {
inOrder(root);
int temp=first.val;
first.val=second.val;
second.val=temp;
}
public void inOrder(TreeNode root){
if(root==null)
return;
inOrder(root.left);
if(first==null&&pre.val>=root.val)
first=pre;
if(first!=null&&pre.val>=root.val)
second=root;
pre=root;
inOrder(root.right);
}
}</span>