
Problem
Solution
Submissions
Recover Binary Search Tree
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C program to recover a binary search tree where exactly two nodes have been swapped by mistake. You need to identify and fix the swapped nodes without changing the structure of the tree. A binary search tree has 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.
Example 1
- Input: root = [1,3,null,null,2]
- Output: [3,1,null,null,2]
- Explanation:
- Original tree has nodes 1 and 3 swapped.
- In correct BST, 3 should be root and 1 should be right child.
- Swap values of nodes 1 and 3 to fix the tree.
- Original tree has nodes 1 and 3 swapped.
Example 2
- Input: root = [3,1,4,null,null,2]
- Output: [2,1,4,null,null,3]
- Explanation:
- Nodes 2 and 3 are swapped in the BST.
- Node 2 should be root, node 3 should be rightmost leaf.
- Swap values of nodes 2 and 3. Tree maintains BST property after swap.
- Nodes 2 and 3 are swapped in the BST.
Constraints
- The number of nodes in the tree is in the range [2, 1000]
- -2^31 ≤ Node.val ≤ 2^31 - 1
- Exactly two nodes are swapped
- Time Complexity: O(n) where n is number of nodes
- Space Complexity: O(h) where h is height of tree for recursion
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use inorder traversal to get sorted sequence of BST values
- In a correct BST, inorder traversal gives sorted array
- Find two nodes that violate the sorted order in inorder sequence
- Keep track of first and second misplaced nodes during traversal
- The first violation gives the larger misplaced node
- The second violation gives the smaller misplaced node
- Swap the values of these two nodes to recover the BST