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個節(jié)點出現(xiàn)的錯誤间唉,就打破了升序绞灼。
- 那么只要找到第一個
current.val < prev.val
,那么prev
就是第一個出錯的節(jié)點 - 然后再找到第二個
current.val < prev.val
呈野,那么prev
就是第二個出錯的節(jié)點
- 那么只要找到第一個
- 交換即可
/**
* 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;
}
}