AlgoInsight

DSA problem

Recover Binary Search Tree

MediumBST / Ordered SetPattern: BST / Ordered Settop600AmazonMicrosoftGoogleBloombergApple

You are given the root of a binary search tree in which exactly two nodes have been swapped by mistake. Recover the tree without changing its structure — only the values of those two nodes may be modified.

Because an in-order traversal of a valid BST yields a strictly increasing sequence, the two swapped values show up as out-of-order pairs in the traversal. The trick is figuring out which two nodes to swap.

If the two swapped nodes are adjacent in the in-order sequence (e.g., [1, 3, 2, 4]), there is exactly one "dip" where prev.val > curr.val. The two culprits are prev and curr from that dip.

If the two swapped nodes are not adjacent in the in-order sequence (e.g., [1, 5, 3, 4, 2, 6] from swapping 5 and 2), there are exactly two dips. The first culprit is the prev of the first dip; the second culprit is the curr of the second dip.

Combining both cases: walk in-order while remembering the previous node. On the first violation record first = prev and second = curr. On any subsequent violation update second = curr (but keep first from the first dip). After the walk, swap the values of first and second. With Morris traversal you can do this in O(n) time and O(1) extra space; the cleaner iterative-stack version uses O(h) auxiliary space.

Examples

Example 1
Input: root = [1,3,null,null,2]
Output: [3,1,null,null,2]
Explanation: The in-order sequence is [1, 3, 2], with one dip at 3 > 2. The two adjacent swapped nodes are 3 and 2; swapping their values restores the BST.
Example 2
Input: root = [3,1,4,null,null,2]
Output: [2,1,4,null,null,3]
Explanation: The in-order sequence is [1, 3, 2, 4], with one dip at 3 > 2. Swap the values 3 and 2 to recover [2,1,4,null,null,3].
Example 3
Input: root = [4,2,6,1,5,3,7]
Output: [4,2,6,1,3,5,7]
Explanation: In-order: [1, 2, 5, 3, 6, 7], dips at 5>3 only — swapping adjacent 5 and 3 fixes it (this example shows the single-dip adjacent case).

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

bsttreeinorderiterative

Browse all DSA problems