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将二叉搜索树中两个元素调换了位置,现在要把二叉搜索树还原成有序。
2首先二叉搜索树有个性质是,对其中序遍历时,得到的序列一定是有序的。
3那么用中序遍历,看得到的序列中乱序的数,然后将其交换
4要求用常数空间,那么用pre指针记录下乱序之处即可
5乱序的情况有两种,只有一处乱序,那么直接交换;还有两处乱序的情况:比如按中序遍历s1,s2,s3,s4;先后发现s1>s2 ,s3>s4,那么就要把s1和s4交换
public static int count=0;
public static TreeNode temp1=null;
public static TreeNode temp2=null;
public static TreeNode temp1Pre=null;
public static TreeNode cur=null;
public static TreeNode pre=null;
public static void recoverTree(TreeNode root) {
if(root==null)return;
count=0;
temp1=null;
temp2=null;
temp1Pre=null;
cur=null;
pre=null;
recoverTree2(root);
if(count==1){
int temp = temp1.val;
temp1.val = temp1Pre.val;
temp1Pre.val = temp;
}
else if(count==2){
int temp = temp1Pre.val;
temp1Pre.val = temp2.val;
temp2.val = temp;
}
}
public static void recoverTree2(TreeNode root) {
if(root==null)return;
if(root.left!=null){
recoverTree2( root.left);
}
if(pre!=null){
if(pre.val>root.val){
if(count==0){
temp1=root;
temp1Pre=pre;
}
else if(count==1){
temp2=root;
}
count++;
}
}
if(root.right!=null){
pre=root;
recoverTree2( root.right);
}
//子节点遍历完,那么如果有root.right,则pre就为上一次pre,否则为root
if(root.right==null){
pre=root;
}
}