Question
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Code
TreeNode pre = null;
TreeNode first = null;
TreeNode second = null;
public void recoverTree(TreeNode root) {
inOrder(root);
int tmp = first.val;
first.val = second.val;
second.val = tmp;
}
public void inOrder(TreeNode root) {
if (root == null) {
return;
}
inOrder(root.left);
if (pre != null && pre.val > root.val) {
if (first == null) {
first = pre;
second = root;
} else {
second = root;
}
}
pre = root;
inOrder(root.right);
}