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 Problem132Input: Wrong BSTInorder: [1,3,2] - Not sorted!Detect & Fix312Output: Correct BSTInorder: [1,2,3] - Sorted ✓Algorithm Steps:1. Inorder traversal2. Find violation points3. Swap the two nodes
Understanding the Visualization
1
Input
BST with two nodes swapped: [1,3,null,null,2]
2
Process
Detect violations in inorder sequence
3
Output
Corrected BST: [3,1,null,null,2]
Key Takeaway
🎯 Key Insight: Use inorder traversal to detect BST violations - exactly two nodes will be out of order
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