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?
package leetCode; /** * Created by lxw, liwei4939@126.com on 2018/3/14. */ public class L099_RecoverBinarySearch { public void recoverTree(TreeNode root){ TreeNode pre = null; TreeNode cur = root; TreeNode first = null; TreeNode second = null; TreeNode tmp = null; while (cur != null){ if (cur.left != null){ tmp = cur.left; while (tmp.right != null && tmp.right != cur){ tmp = tmp.right; } if (tmp.right == null){ tmp.right = cur; cur = cur.left; } else { if (pre != null && pre.val > cur.val){ if (first == null){ first = pre; second = cur; } else { second = cur; } } pre = cur; tmp.right = null; cur = cur.right; } } else { if (pre != null && pre.val > cur.val){ if (first == null){ first = pre; second = cur; } else { second = cur; } } pre = cur; cur = cur.right; } } if (first != null && second != null){ first.val ^= second.val; second.val ^= first.val; first.val ^= second.val; } } }二叉树的Morris遍历参考 http://www.cnblogs.com/AnnieKim/archive/2013/06/15/morristraversal.html