Recover Binary Search Tree - Problem

You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.

A binary search tree satisfies the property that for every node, all values in the left subtree are less than the node's value, and all values in the right subtree are greater than the node's value.

Your task is to identify the two swapped nodes and correct their values to restore the BST property.

Input & Output

Example 1 — Adjacent Swap
$ Input: root = [1,3,null,null,2]
Output: [3,1,null,null,2]
💡 Note: The values 1 and 3 were swapped. After correction: 3 should be root with 1 as left child and 2 as right child of 1.
Example 2 — Non-Adjacent Swap
$ Input: root = [3,1,4,null,null,2]
Output: [2,1,4,null,null,3]
💡 Note: Values 3 and 2 were swapped. The BST should have 2 as root, with 1 as left child and 4 as right child, and 3 as left child of 4.

Constraints

  • The number of nodes in the tree is in the range [2, 1000]
  • -231 ≤ Node.val ≤ 231 - 1

Visualization

Tap to expand
Recover Binary Search Tree INPUT Broken BST (nodes swapped) 1 3 2 Swapped nodes Correct node root = [1,3,null,null,2] ALGORITHM STEPS (Two-Pass DFS) 1 Inorder Traversal Get sequence: 3,2,1 2 Find First Violation 3 > 2 (first node = 3) 3 Find Second Violation 2 > 1 (second node = 1) 4 Swap Values Swap node 1 and node 3 Inorder sequence: 3 2 1 Wrong! Time: O(n) | Space: O(h) h = height of tree FINAL RESULT Recovered BST 3 1 2 BST Property: OK Inorder: 1,2,3 (sorted) [3,1,null,null,2] Key Insight: In a valid BST, inorder traversal produces a sorted sequence. When two nodes are swapped, we find violations where a node is greater than its successor. The first violation's predecessor and the last violation's successor are the two swapped nodes. Swap their values to recover the BST. TutorialsPoint - Recover Binary Search Tree | Two-Pass DFS (Morris-like)
Asked in
Amazon 15 Microsoft 12 Google 8
182.0K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen