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,其中序遍历序列是一个递增序列,假设A,B节点互换了位置,则在中序遍历中A比其后元素大,B比前面元素小,可据此性质找出AB节点并调换回来。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { // Method 2: recursive TreeNode prev, p, q; public void recoverTree(TreeNode root) { inorder(root); if (p != null) { int tmp = p.val; p.val = q.val; q.val = tmp; } } public void inorder(TreeNode root) { if (root == null) return; inorder(root.left); if (prev != null && prev.val > root.val) { if (p == null) p = prev; q = root; } prev = root; inorder(root.right); } // Method 1: iterative public void recoverTree1(TreeNode root) { if (root == null) return; LinkedList<TreeNode> stack = new LinkedList<TreeNode>(); TreeNode curr = root, prev = null; TreeNode errPair1First = null, errPair1Sec = null; TreeNode errPair2Sec = null; while (!stack.isEmpty() || curr != null) { if (curr != null) { stack.push(curr); curr = curr.left; } else { curr = stack.pop(); if (prev != null && prev.val > curr.val) { if (errPair1First == null) { errPair1First = prev; errPair1Sec = curr; } else { errPair2Sec = curr; break; } } prev = curr; curr = curr.right; } } if (errPair2Sec == null) { swap(errPair1First, errPair1Sec); } else { swap(errPair1First, errPair2Sec); } } private void swap (TreeNode node1, TreeNode node2) { int tmp = node1.val; node1.val = node2.val; node2.val = tmp; } }