56. Recover Binary Search Tree

56. Recover Binary Search Tree

Hard
38.0%
2.9k
dfsbfsbinary-searchtreebinary-treerecursion
Google, Amazon, Netflix, Meta (Facebook), Apple, Microsoft, Uber, Bloomberg, Airbnb, Stripe, Adobe, Salesforce, LinkedIn, Oracle

A large-scale system maintains critical ordered datasets using a Binary Search Tree (BST), where:

  • left subtree contains smaller values
  • right subtree contains larger values

Due to a system bug, exactly two nodes in the BST have been swapped, violating the BST property.

This issue can lead to:

  • incorrect query results
  • invalid ranking systems
  • broken ordering guarantees

The system needs a recovery mechanism that:

  • identifies the two misplaced nodes
  • restores the BST without changing the tree structure

⚠️ Constraint:
You must fix the tree in-place, without rebuilding it.

This is a classic advanced interview problem frequently asked in Google, Amazon, Meta, Microsoft, and other top companies.

Your Task

Given the root of a BST where exactly two nodes are swapped by mistake:

👉 Recover the tree by swapping the values of the two nodes back.

Do not change the tree structure, only modify node values.

Input Format

  • root: root node of a BST

Each node:

TreeNode { int val; TreeNode left; TreeNode right;}

Output Format

  • Return the root of the corrected BST

Examples

Example 1:

Input: 1 / 3 \ 2
Output: 3 / 1 \ 2
Explanation: Nodes 1 and 3 were swapped

Example 2:

Input: 3 / \ 1 4 / 2
Output: 2 / \ 1 4 / 3

Constraints

  • 2 ≤ number of nodes ≤ 100,000
  • -10^9 ≤ Node.val ≤ 10^9
  • Exactly two nodes are swapped
  • Must use O(1) extra space (follow-up expectation)

Loading editor...

[1,3,null,null,2]
[3,1,null,null,2]

Console Output

Click "Run Code" or "Submit" to see results

Your code will be evaluated by AI with instant feedback