Recover binary search tree solution explained

In Recover Binary Search Tree, two nodes' values were swapped and you must restore the tree without changing its shape. An inorder walk of a valid BST is sorted, so the swap shows up as one or two places where a value is larger than the next: the first misplaced node is the larger value at the first such drop, the second is the smaller value at the last drop. Swap their values back. With an explicit stack that is O(n) time and O(h) space, and Morris traversal makes the space O(1).

By Published 7 min read

The problem in plain words

You get the root of a binary search tree in which exactly two nodes have had their values exchanged by mistake. Everything else is correct. Fix the tree in place by restoring the two values, without moving any node or changing any link. Nothing is returned.

Broken:                    Fixed:
         8                          8
       /   \                      /   \
      3     5                    3     12
     / \   / \                  / \   /  \
    1  12 10  14               1   5 10   14

Inorder of the broken tree:  1, 3, 12, 8, 10, 5, 14
Drops:                              12 > 8      10 > 5
Our example: 5 and 12 were swapped

The inorder sequence has two drops. At the first, the larger value 12 is the intruder that moved left. At the second, the smaller value 5 is the one that moved right. Exchange those two values and the sequence is sorted again: 1, 3, 5, 8, 10, 12, 14.

If the swapped nodes are neighbors in inorder, there is only one drop. Swapping 8 and 10 in the fixed tree, for instance, gives 1, 3, 5, 10, 8, 12, 14. The first and last drops are then the same drop, and its two nodes are the pair to fix. Code that only handles the two-drop case fails here.

Why it gets asked

The problem checks whether you connect a BST to its sorted inorder sequence instead of trying to reason about subtrees and bounds. It then layers two follow-ups: handle the adjacent case cleanly, and reduce memory. The second is the classic reason interviewers ask about Morris traversal at all.

Simple fix: sort the values and write them back

Collect the nodes in inorder. Their values should be sorted but are not. Sort the values alone, then assign the sorted values to the nodes in the same inorder order. Because only two values are out of place, this rewrites exactly those two and leaves the rest as they were. It is easy to trust and costs O(n log n) time and O(n) space.

class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right


def recover_by_sorting(root):
    nodes = []

    def inorder(node):
        if node:
            inorder(node.left)
            nodes.append(node)
            inorder(node.right)

    inorder(root)
    for node, val in zip(nodes, sorted(n.val for n in nodes)):
        node.val = val          # write the sorted values back in inorder positions
Python, sort and write back. O(n log n) time, O(n) space.

One pass: find the two nodes during inorder

Sorting is wasteful because you already know the sequence is almost sorted. Walk it once, remembering the previous node. Whenever the previous value is greater than the current one, you have a drop. The first time that happens, the previous node is the first culprit. Every time it happens, update the second culprit to the current node; after the walk, it holds the smaller value from the last drop, which covers both the adjacent and the distant case. Swap the two values.

def recover_tree(root):
    first = second = prev = None
    stack, node = [], root
    while stack or node:
        while node:                         # iterative inorder walk
            stack.append(node)
            node = node.left
        node = stack.pop()
        if prev and prev.val > node.val:    # a descent: something is out of place
            if first is None:
                first = prev                # the too-big value, at the first descent
            second = node                   # the too-small value, at the last descent
        prev = node
        node = node.right
    first.val, second.val = second.val, first.val
Python, iterative inorder with a stack. O(n) time, O(h) space.
function recoverTree(root) {
  let first = null, second = null, prev = null;
  const stack = [];
  let node = root;
  while (stack.length > 0 || node) {
    while (node) {
      stack.push(node);
      node = node.left;
    }
    node = stack.pop();
    if (prev && prev.val > node.val) {
      if (!first) first = prev;
      second = node;
    }
    prev = node;
    node = node.right;
  }
  [first.val, second.val] = [second.val, first.val];
}
JavaScript, the same walk.

Follow-up: O(1) space with Morris inorder

The stack is the only extra memory left. Morris traversal replaces it with temporary threads: for a node with a left subtree, find that subtree's rightmost node and point its right pointer back at the node. Follow the thread later to climb back, removing it on the way. Inorder visits a node when it arrives with no left subtree or comes back up its thread, and the drop check runs at exactly that moment.

def recover_tree_morris(root):
    first = second = prev = None
    node = root
    while node:
        if node.left:
            pred = node.left
            while pred.right and pred.right is not node:
                pred = pred.right
            if pred.right is None:          # thread and go left; visit later
                pred.right = node
                node = node.left
                continue
            pred.right = None               # came back up the thread
        if prev and prev.val > node.val:    # visit node in inorder position
            if first is None:
                first = prev
            second = node
        prev = node
        node = node.right
    first.val, second.val = second.val, first.val
Python, Morris inorder. O(n) time, O(1) extra space; all threads are removed.

Complexity

n nodes, height h
ApproachTimeExtra space
Sort values, write backO(n log n)O(n)
Inorder with a stack, track dropsO(n)O(h)
Morris inorder, track dropsO(n)O(1)
n nodes, height h. Scroll sideways on a small screen.

Edge cases to test

  • The two swapped nodes are neighbors in inorder (one drop).
  • The root is one of the swapped nodes.
  • A swap between the smallest and the largest value, the farthest apart possible.
  • A two-node tree, where the only possible swap is between parent and child.
  • A tall, one-sided tree, which is where the stack version's O(h) is largest.

Common mistakes

  • Setting the second culprit only on the second drop, which leaves it empty when the swapped nodes are adjacent.
  • Recording the current node at the first drop instead of the previous one.
  • Swapping node objects or links instead of values, which breaks the shape the problem asks you to keep.
  • Checking each node only against its parent; a swap can hide between non-adjacent levels.
  • In the Morris version, running the drop check when creating a thread rather than when visiting the node.

How to explain it out loud

Fictional example

Talking through the one-pass solution
Candidate
An inorder walk of a correct BST is sorted. Swapping two values creates one or two spots where a value is bigger than the next.
Candidate
The first wrong node is the bigger value at the first drop. The second is the smaller value at the last drop. If they are adjacent, both come from the same drop, so I update the second one on every drop.
Candidate
One inorder walk with a previous pointer: O(n) time, O(h) for the stack. If memory matters, I can do the same walk with Morris threading in constant space.

Another repair that leans on BST order is Trim a Binary Search Tree. The threading trick used here also appears in Binary Tree Preorder Traversal, where Morris records nodes on the way down instead. For a tree problem on a general graph rather than a BST, try Minimum Height Trees, or browse the coding problems hub.

Practicing with Natively

The adjacent-swap case is the one people miss in practice. Natively can read your broken tree from a screenshot on Mac or Windows, list its inorder sequence with the drops marked, and test your rule on both the adjacent and the distant case. Reviewing the transcript of a mock afterwards shows whether you raised that case yourself or waited to be asked.

Questions people ask

How do you recover a binary search tree with two swapped nodes?

Walk the tree in inorder, which should be sorted. The first misplaced node is the larger value at the first drop and the second is the smaller value at the last drop. Swap their values.

What if the two swapped nodes are adjacent in inorder?

There is only one drop. Updating the second node on every drop, not only on the second one, handles this case automatically.

Can you recover a BST in O(1) space?

Yes, with Morris inorder traversal, which uses temporary threads instead of a stack and removes them as it goes. Time stays O(n).

What is the simplest correct solution?

Collect the nodes in inorder, sort their values and write them back in the same order. It costs O(n log n) time and O(n) space.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP