Tutorialspoint
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.
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.
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
TreeEYPhillips
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Initialize global variables to track first misplaced node, second misplaced node, and previous node

 Step 2: Perform inorder traversal of the BST to visit nodes in sorted order
 Step 3: During traversal, compare each node with the previous node to detect violations
 Step 4: When first violation is found (prev > current), mark the previous node as first misplaced node
 Step 5: Continue traversal to find second violation and mark current node as second misplaced node
 Step 6: After traversal completes, swap the values of the two misplaced nodes
 Step 7: The BST is now recovered with correct node values maintaining BST property

Submitted Code :