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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code