• Courses
  • Tutorials
  • Jobs
  • Practice
  • Contests
July 04, 2022 |7.6K Views
Two nodes of a BST are swapped, correct the BST
  Share   Like
Description
Discussion

Two of the nodes of a Binary Search Tree (BST) are swapped. Fix (or correct) the BST.

Input Tree:
        10
       /  \
      5    8
     / \
    2   20

In the above tree, nodes 20 and 8 must be swapped to fix the tree.  
Following is the output tree
        10
       /  \
      5    20
     / \
    2   8

 

Since in-order traversal of BST is always a sorted array, the problem can be reduced to a problem where two elements of a sorted array are swapped.

There are two cases that to handle:

Maintain three-pointers, first, middle, and last. When the first point where the current node value is smaller than the previous node value is found, update the first with the previous node & the middle with the current node. 


When we find the second point where the current node value is smaller than the previous node value, we update the last with the current node. If the last node value is null, then two swapped nodes of BST are adjacent i.e. first and middle otherwise first and last


Two nodes of a BST are swapped, correct the BST : https://www.geeksforgeeks.org/fix-two-swapped-nodes-of-bst

Read More