题目:
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?
解答:
想法很简单,找到两个顺序不对的点,交换。但是如何知道这两个点的顺序是不对的呢?因为BST是左<中<右,所以我们可以用in-order traverse的方法:
In-order traverse模板:
public void inOrderTraverse{
inOrderTraverse(root.left);
//do something
inOrderTraverse(root.right);
}
代码如下:
public class Solution {
private TreeNode first = null, second = null;
private TreeNode prev = new TreeNode(Integer.MIN_VALUE);
public void recoverTree(TreeNode root) {
Traverse(root);
int temp = first.val;
first.val = second.val;
second.val = temp;
}
public void Traverse(TreeNode root) {
if (root == null) return;
Traverse(root.left);
if (first == null && prev.val > root.val) {
first = prev;
}
if (first != null && prev.val > root.val) {
second = root;
}
prev = root;
Traverse(root.right);
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。