题目
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中序遍历结果的升序特性,可以找到逆序对,这里要注意两种情况:
1. 如果交换节点刚好在中序遍历时,是相邻的,那么只有一个逆序对;
2. 如果不相邻,就有两个逆序对
代码
public class RecoverBinarySearchTree {
private TreeNode first;
private TreeNode second;
private TreeNode preNode;
public void recoverTree(TreeNode root) {
first = null;
second = null;
preNode = null;
inorder(root);
assert first != null && second != null;
int temp = first.val;
first.val = second.val;
second.val = temp;
}
private void inorder(TreeNode root) {
if (root == null) {
return;
}
inorder(root.left);
if (preNode != null && root.val < preNode.val) {
if (first == null) {
first = preNode;
}
second = root;
}
preNode = root;
inorder(root.right);
}
}