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?
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
这题关键在于inorder traversal. 首先需要3个全局指针pre,first,second。 pre始终指向traversal当前node的前一个,first是第一个错误的点,second是第二个错误的点。
注意点:两个错误点可能是相邻的,也可能是不相邻的。当第一次发现错误点的时候, first = pre, second = root, 把两个错误点都设了,防止之后没有错误点了,那么就是这两个了。
如果之后还有错误点,只更新 second 即可。
static TreeNode pre = null, first = null, second = null;
public static void recoverTree(TreeNode root) {
recoverTreeHelper(root);
if (first != null && second != null) {
int temp = first.val;
first.val = second.val;
second.val = temp;
}
}
public static void recoverTreeHelper(TreeNode root) {
if (root == null) return;
recoverTreeHelper(root.left);
if (pre == null) pre = root;
else if (root.val < pre.val) {
if (first == null) {
first = pre;
}
second = root;
}
pre = root;
recoverTreeHelper(root.right);
}