Recover Binary Search Tree
Two values in a binary search tree were swapped by mistake; find them and swap them back.
In a binary search tree, the values of exactly two nodes were swapped by mistake. Swap them back so the tree is a valid binary search tree again, without changing its shape: only node values may change. Trees are written row by row, top to bottom and left to right, with null
Example 1
Output: [3, 1, null, null, 2]
Explanation: 3 cannot sit on the left side of 1; swapping 1 and 3 fixes it.
Example 2
Output: [2, 1, 4, null, null, 3]
Explanation: 2 cannot sit on the right side of 3; swapping 2 and 3 fixes it.
The Idea
Picture a shelf of books sorted by title, where someone swapped two of them. You would not rebuild the shelf. You would walk along it, notice where the order breaks, and put the two books back. This problem is the same, except that the shelf is a tree.
Start with the fixed tree of Example 2, [2, 1, 4, null, null, 3]
The input tree of Example 2, [3, 1, 4, null, null, 2]
A binary search tree can be read so that its values come out from smallest to largest. For each node, read everything on its left side first, then the node itself, then everything on its right side. This order of visiting is called an in-order traversal. The fixed tree of Example 2 reads 1, 2, 3, 4.
Since a correct tree reads in sorted order, a swap shows up as a break in that order. Look at the picture below.
On the left is the input tree of Example 2, with the swapped 3 and 2 in orange. Read in order, it gives the row labelled "Example 2 in order: one drop": 1, 3, 2, 4. Call a place where a value is smaller than the one just before it a drop. Here there is one, 3 > 2, and swapping its two values gives 1, 2, 3, 4.
Now the lower row, "Example 1 in order: two drops". Example 1's tree reads 3, 2, 1, and it has a first drop, 3 > 2, and a last drop, 2 > 1. The swapped values are 3 and 1, which have 2 between them. The 3 belongs at the end of the row but sits at the start, so it is bigger than the value after it and starts the first drop. The 1 belongs at the start but sits at the end, so it ends the last drop.
That gives one rule for both rows: the swapped pair is the bigger value of the first drop and the smaller value of the last drop. With only one drop, as in Example 2, the first and the last drop are the same one.
Solution Approach
Turning the drop rule into code means settling three things: how to visit the nodes in sorted order, how to spot the two swapped nodes during that visit, and how to put them back. A simpler but slower way, and an optional way to save memory, are worth knowing too.
Visiting the nodes in sorted order
How do we read the tree in order? A method that calls itself fits well: for a node, it first calls itself on the left child, then handles the node, then calls itself on the right child. When it reaches a missing child, it returns at once.
To spot a drop, each node must be compared with the node read just before it. So the method keeps that earlier node in a field, prev
Spotting the swapped nodes
What should happen at a drop? Two more fields hold the answer: firstsecondfirstprevsecond
Why not set both at the first drop and stop? In Example 1, which reads 3, 2, 1, that would pick 3 and 2. Swapping them gives 2, 3, 1, which is still not sorted. Updating second
Putting the values back
Once the reading is done, the two nodes trade values. The nodes themselves stay where they are, with the same children, so the shape of the tree does not change, as the problem requires.
The simpler way: copy and sort
Is there a way that needs no drop rule? Read all the values in order into a list, sort the list, and write the values back into the nodes in the same order. That works, but it keeps a copy of every value and spends O(n log n) time sorting n values, while the drop rule needs one pass.
Optional: reading without a call stack
Each call that has not finished yet takes some memory, and the unfinished calls belong to the nodes on the path from the root to the current node. So the method above uses memory that grows with the height of the tree, the number of nodes on its longest path from the root down. A technique called Morris traversal reads the tree in order without those unfinished calls. Before going down a left side, it links the last node of that side back to the current node, follows that link to come back, and then removes it. The drop rule stays the same.
Java Solution
The method recoverTree
- First, set the three fields
,first andsecond toprev , so nothing from an earlier call is left over.null - Call
. The methodinorder(root) returns at once wheninorder(node) isnode . Otherwise it calls itself onnull , so all the smaller values are read first.node.left - Back at
, compare it withnode . Ifprev , this is a drop: setprev.val > node.val tofirst ifprev is stillfirst , and setnull tosecond in any case.node - Set
toprev , then callnode oninorder .node.right - When the reading is done, swap
andfirst.val through a temporary variablesecond.val .t
A small TreeNodebuildtoListmain
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class RecoverBST {
static class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
private TreeNode first; // bigger value of the first drop
private TreeNode second; // smaller value of the latest drop
private TreeNode prev; // node visited just before the current one
public void recoverTree(TreeNode root) {
first = second = prev = null;
inorder(root);
int t = first.val;
first.val = second.val;
second.val = t;
}
private void inorder(TreeNode node) {
if (node == null) {
return;
}
inorder(node.left);
if (prev != null && prev.val > node.val) {
if (first == null) {
first = prev; // first drop: the bigger value is out of place
}
second = node; // every drop: the smaller value may be out of place
}
prev = node;
inorder(node.right);
}
// Builds a tree from the row-by-row form, with null for a missing child.
static TreeNode build(Integer[] a) {
TreeNode root = new TreeNode(a[0]);
Queue<TreeNode> q = new ArrayDeque<>(List.of(root));
for (int i = 1; i < a.length; i += 2) {
TreeNode n = q.poll();
if (a[i] != null) {
n.left = new TreeNode(a[i]);
q.add(n.left);
}
if (i + 1 < a.length && a[i + 1] != null) {
n.right = new TreeNode(a[i + 1]);
q.add(n.right);
}
}
return root;
}
// Writes a tree back in the same row-by-row form.
static List<Integer> toList(TreeNode root) {
List<Integer> out = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
TreeNode n = q.poll();
out.add(n == null ? null : n.val);
if (n != null) { q.add(n.left); q.add(n.right); }
}
while (out.get(out.size() - 1) == null) {
out.remove(out.size() - 1);
}
return out;
}
static void run(Integer... values) {
TreeNode root = build(values);
new RecoverBST().recoverTree(root);
System.out.println(Arrays.toString(values) + " -> " + toList(root));
}
public static void main(String[] args) {
run(1, 3, null, null, 2);
run(3, 1, 4, null, null, 2);
run(1, 2);
run(4, 2, 6, 7, 3, 5, 1);
run(4, 2, 6, 1, 5, 3, 7);
}
}
Running it prints:
[1, 3, null, null, 2] -> [3, 1, null, null, 2]
[3, 1, 4, null, null, 2] -> [2, 1, 4, null, null, 3]
[1, 2] -> [2, 1]
[4, 2, 6, 7, 3, 5, 1] -> [4, 2, 6, 1, 3, 5, 7]
[4, 2, 6, 1, 5, 3, 7] -> [4, 2, 6, 1, 3, 5, 7]
Each line shows the tree before the arrow and after it. In the first line, Example 1's [1, 3, null, null, 2][3, 1, null, null, 2][1, 2][2, 1]
Look at the fourth line. Its input reads 7, 2, 3, 4, 5, 6, 1, with drops 7 > 2 at the very start and 6 > 1 at the very end. The two swapped nodes are as far apart as they can be, at the bottom left and bottom right, and the output puts 1 and 7 back in those places.
The last line reads 1, 2, 5, 4, 3, 6, 7. Its drops are 5 > 4 and 4 > 3, so the 4 appears in both. Yet only 5 and 3 trade places, and the output is the same tree as on the line above.
Complexity
The work is one in-order reading of the tree plus one swap of two values.
- Time: O(n), because the in-order reading visits each of the n nodes once and makes one comparison there, and the final swap is a single step.
- Space: O(h), because the unfinished calls belong to the nodes on the path from the root down to the current node, and that path is at most the tree's height h, which is n for one long chain.
Reading a binary search tree in order also checks whether a tree follows the rule at all: see