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?
Subscribe to see which companies asked this question.
一个思路是找到被交换的两个点,然后交换这两个点的值。
现在有两种解法,一个是用了Morris Traversal, 还有一种是直接采用中序遍历。
Morris Traversal先放着。。先解释后一种直观的解法。
先上代码
public class Solution {
TreeNode first = null;
TreeNode second = null;
TreeNode pre = new TreeNode(Integer.MIN_VALUE);
public void recoverTree(TreeNode root) {
if(root==null) return;
transe(root);
if(first!=null){
int tp = first.val;
first.val = second.val;
second.val = tp;
}
}
public void transe(TreeNode root){
if(root==null) return;
transe(root.left);
//start convert
if(first==null&&pre.val >= root.val) first = pre;
if(first!=null&&pre.val >= root.val) second = root;
pre = root;
transe(root.right);
}
}
这里有三个指针,first, second, pre。在遍历过程中时按照左,根,右的次序。其中pre记录的是遍历过程中根的值,如果BST没有问题的话,那么在遍历完左子树后,pre.val < root.val。那么firt, second都不会更新,都是null。
但是如果有个错误的点在某个节点的左孩子中的话,那么必然会出现pre.val > root.val的情况,因为遍历顺序是根,左,右,左右这样找到的必定是第一个,记为first。
如果有个错误的点出现在右子树中,那么pre记录的是父节点,那么pre.val >= root.val。
等号出现的情况就是出现在根上和子树上各一个。