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 where a child is missing.

Example 1
Input: root = [1, 3, null, null, 2]
Output: [3, 1, null, null, 2]
Explanation: 3 cannot sit on the left side of 1; swapping 1 and 3 fixes it.
Example 2
Input: root = [3, 1, 4, null, null, 2]
Output: [2, 1, 4, null, null, 3]
Explanation: 2 cannot sit on the right side of 3; swapping 2 and 3 fixes it.
Solution

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]. Its top node, the root, holds 2. The root's left child, 1, is smaller than 2. Its right child, 4, and the 3 hanging below 4 on the left are both bigger. Node 4 follows the same rule: 3, on its left, is smaller than 4. A tree where every node has only smaller values on its left side and only bigger values on its right side is a binary search tree.

The input tree of Example 2, [3, 1, 4, null, null, 2], breaks that rule: the root holds 3, but 2 sits on its right side. In a tree this small the problem is easy to spot. But in a bigger tree, how do we tell which two nodes were swapped?

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.

The Example 2 tree has root 3, left child 1, right child 4, and 2 as the left child of 4; 3 and 2 were swapped. Read in order it gives 1, 3, 2, 4, with one drop from 3 to 2. Example 1 read in order gives 3, 2, 1, with a first drop and a last drop; swapping 3 and 1 fixes it.

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, and updates it after handling each node.

Spotting the swapped nodes

What should happen at a drop? Two more fields hold the answer: first for the bigger value of the first drop, and second for the smaller value of the last drop. At the first drop, first is set to prev, and it never changes after that. second is set to the current node at every drop, so when the reading ends, it holds the node from the last drop.

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 at every drop picks 1 instead.

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 works in these steps:

  1. First, set the three fields first, second and prev to null, so nothing from an earlier call is left over.
  2. Call inorder(root). The method inorder(node) returns at once when node is null. Otherwise it calls itself on node.left, so all the smaller values are read first.
  3. Back at node, compare it with prev. If prev.val > node.val, this is a drop: set first to prev if first is still null, and set second to node in any case.
  4. Set prev to node, then call inorder on node.right.
  5. When the reading is done, swap first.val and second.val through a temporary variable t.

A small TreeNode class holds a value and two children, build makes a tree from the row-by-row form, and toList writes a tree back in that form. The main method fixes both examples, a tree of two nodes, a tree of seven nodes whose smallest and largest values were swapped, and the same tree with 3 and 5 swapped instead.

Java
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:

Output
[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] becomes [3, 1, null, null, 2], the 3 and 1 picked by the first and last drop. The third line is the smallest case: in [1, 2], the 2 is the left child of the 1, so the tree reads 2, 1. That single drop gives [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 Validate BST.