Problem
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Example 1:
1 |
|
Example 2:
1 |
|
Follow up:
- A solution using O(n) space is pretty straight forward.
- Could you devise a constant space solution?
Explanation 1
-
If we use O(n) space, we can use in-order traversal method to solve this problem. In a valid BST, if we use in-order traversal, all traversaled elements should be sorted, if it is not sorted, then this is not a valid BST.
-
If the correct valid BST is
[1, 2, 3, 4, 5, 6, 7, 8]
, if two elements are swaped mistake, let say 2 and 6 are swapped so we want to create two new variable to record 2 and 6, let sayfirst
andsecond
, and now the traversal elements become[1, 6, 3, 4, 5, 2, 7, 8]
. We find out 6 and 3 are not sorted in order (first is 6, second is 3), also 5 and 2 are not sorted in order (first remains 6, second is 2). So we swapfirst
andsecond
and we are done.
Solution 1
1 |
|
Explanation 2
- If we want O(1) space, then we can apply morris traversal method.
Solution 2
1 |
|