题目
恢复BST,有两个点交换了。
代码
public class Solution {
public void recoverTree(TreeNode root) {
if(root == null){
return ;
}
ArrayList<TreeNode> record = new ArrayList<TreeNode>();
TreeNode first = null;
TreeNode second = null;
useme(record,root);
for(int i=1;i<record.size();i++){
if(record.get(i-1).val>record.get(i).val){
if(first == null){
first = record.get(i-1);
second = record.get(i);
}
else{
second = record.get(i);
}
}
}
int temp = first.val;
first.val = second.val;
second.val = temp;
return;
}
public void useme(ArrayList<TreeNode> record , TreeNode root){
if(root!=null){
useme(record,root.left);
record.add(root);
useme(record,root.right);
}
}
}
依然可以用inorder遍历的方法,转换为一个递增数组中,找到交换顺序的两个数。
上面的方法需要O(n)的空间,那么减少空间的方法,就是使用 Morris 中序遍历,定义再维基,百度都有,直接贴代码
public class Solution {
public void recoverTree(TreeNode root) {
if(root == null){
return ;
}
TreeNode pre = null;
TreeNode cur = root;
TreeNode first = null;
TreeNode second = null;
TreeNode a =null;
TreeNode b = null;
while(cur!=null){
if(cur.left==null){
if(first ==null) first = cur;
else if(second == null) second = cur;
else{
first = second;
second = cur;
}
cur = cur.right;
}
else{
pre = cur.left;
while(pre.right!=null && pre.right!=cur) pre = pre.right;
if(pre.right == null){
pre.right = cur;
cur = cur.left;
continue;
}
else{
pre.right = null;
if(second == null) second = cur;
else{
first = second;
second = cur;
}
cur = cur.right;
}
}
if(first!=null && second!=null && first.val > second.val){
if(a == null) a = first;
b = second;
}
}
int temp = a.val;
a.val = b.val;
b.val = temp;
}
}