原题:https://oj.leetcode.com/problems/recover-binary-search-tree/
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?
思路总结:
说到底还是找到规律:
假设正常的二叉排序树的中序遍历结果是1,2,3,4,5,6,7,8,9
现在错误的是1,2,8,4,5,6,7,3,9
规律是:
第一次出现后小于前的,前面那个是被交换的一个(8);
第二次出现后小于前的,后面那个是被交换的另一个(3);
对root中序遍历一次,并找出它们然后交换一下就解决问题了
AC代码:
public class RecoverBinarySearchTree {
private TreeNode firstWrong = null;
private TreeNode secondWrong = null;
private TreeNode last = new TreeNode(Integer.MIN_VALUE);
public void recoverTree(TreeNode root) {
if(root == null) return;
inOrder(root);
int temp = firstWrong.val;
firstWrong.val = secondWrong.val;
secondWrong.val = temp;
}
public void inOrder(TreeNode root) {
if(root.left != null) inOrder(root.left);
if(root.val < last.val && firstWrong == null) {
firstWrong = last;
}
if(root.val < last.val && firstWrong != null) {
secondWrong = root;
}
last = root;
if(root.right != null) inOrder(root.right);
}
}