Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Example 1:
Input: [1,3,null,null,2]
1
/
3
\
2
Output: [3,1,null,null,2]
3
/
1
\
2
Example 2:
Input: [3,1,4,null,null,2]
3
/ \
1 4
/
2
Output: [2,1,4,null,null,3]
2
/ \
1 4
/
3
Follow up:
- A solution using O(n) space is pretty straight forward.
- Could you devise a constant space solution?
Solution: InOrder Traverse
- 用中序遍历 (正常时遍历的值为升序)
- 但是有2个节点出现的错误,就打破了升序。
- 那么只要找到第一个
current.val < prev.val
,那么prev
就是第一个出错的节点 - 然后再找到第二个
current.val < prev.val
,那么prev
就是第二个出错的节点
- 那么只要找到第一个
- 交换即可
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public void recoverTree(TreeNode root) {
TreeNode first = null;
TreeNode second = null;
TreeNode prev = null;
Stack<TreeNode> tracker = new Stack<> ();
TreeNode current = root;
while (!tracker.isEmpty () || current != null) {
if (current != null) {
tracker.push (current);
current = current.left;
} else {
current = tracker.pop ();
// find the two nodes which have been swapped incorrectly
// cannot use if else here, for example [3,1,4,null,null,2], which in-order is 1 3 2 4, prev: 3, current 2.
// the first and second nodes are found at the same time. so we cannot use if else.
if (prev != null && current.val < prev.val) {
if (first == null)
first = prev;
second = current;
}
prev = current;
current = current.right;
}
}
int temp = first.val;
first.val = second.val;
second.val = temp;
}
}
网友评论