Difficulty: Hard
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Example 1:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 
 | Input: [1,3,null,null,2]
 1
 /
 3
 \
 2
 
 Output: [3,1,null,null,2]
 
 3
 /
 1
 \
 2
 
 | 
Example 2:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 
 | 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
Language: Java
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 
 | 
 
 
 
 
 
 
 
 class Solution {
 private TreeNode first, second, prev;
 public void recoverTree(TreeNode root) {
 if (root == null) {
 return;
 }
 prev = new TreeNode(Integer.MIN_VALUE);
 inorder(root);
 
 int tmp = first.val;
 first.val = second.val;
 second.val = tmp;
 }
 
 private void inorder(TreeNode root) {
 if (root == null) {
 return;
 }
 inorder(root.left);
 
 if (first == null && root.val <= prev.val) {
 first = prev;
 }
 
 if (first != null && root.val <= prev.val) {
 second = root;
 }
 
 prev = root;
 inorder(root.right);
 }
 }
 
 |