Recover Binary Search Tree
Two elements of a binary search tree (BST) are swapped by mistake.
Tell us the 2 values swapping which the tree will be restored.
Note:
A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
Example :
Input :
1
/ \
2 3
Output :
[1, 2]
Explanation : Swapping 1 and 2 will change the BST to be
2
/ \
1 3
which is a valid BST
Solution:
Time: O(n)
Space: O(h)
/**
* Definition for binary tree
* class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) {
* val = x;
* left=null;
* right=null;
* }
* }
*/
public class Solution {
public ArrayList<Integer> recoverTree(TreeNode A) {
Integer prev = null;
Integer one = null;
Integer two = null;
ArrayList<Integer> result = new ArrayList<>();
Deque<TreeNode> stack = new ArrayDeque<>();
TreeNode curr = A;
while (curr != null || !stack.isEmpty()) {
while (curr != null) {
stack.push(curr);
curr = curr.left;
}
if (!stack.isEmpty()) {
curr = stack.pop();
int val = curr.val;
if (prev != null) {
if (prev > val) {
if (one == null) {
one = prev;
}
two = val;
}
}
prev = val;
curr = curr.right;
}
}
result.add(two);
result.add(one);
return result;
}
}