GFG App
Open App
Browser
Continue

# Two nodes of a BST are swapped, correct the BST

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

Input: x = 20, y = 8
10
/  \
5    8
/ \
2   20
Output:
10
/  \
5    20
/ \
2   8

Input: x = 10 y = 5
10
/  \
5    8
/ \
2   20
Output:
5
/  \
10   20
/ \
2   8

Approach:

The in-order traversal of a BST produces a sorted array. So a simple method is to store inorder traversal of the input tree in an auxiliary array. Sort the auxiliary array. Finally, insert the auxiliary array elements back to the BST, keeping the structure of the BST same.

## C++

 // C++ Program for the above approach #include using namespace std;   struct Node{     int data;     Node* left;     Node* right;     Node(int data){         this->data = data;         this->left = this->right = NULL;     } };   Node* newNode(int data){     return new Node(data); }   void storeInVector(Node* root, vector&vec){     if(root == NULL) return;     storeInVector(root->left, vec);     vec.push_back(root->data);     storeInVector(root->right, vec); }   void correctBSTUtil(Node* root, vector &vec, int &index){     if(root == NULL) return;     correctBSTUtil(root->left, vec, index);     root->data = vec[index];     index++;     correctBSTUtil(root->right, vec, index); }   void correctBST(Node* root){     // vector to store the inorder traversal of     // given tree     vector vec;     storeInVector(root, vec);     sort(vec.begin(), vec.end());     int index = 0;     correctBSTUtil(root, vec, index); }   void printInorder(Node* root){     if(root == NULL) return;     printInorder(root->left);     cout<data<<" ";     printInorder(root->right); }   int main(){     /*   6         / \        10  2       / \ / \      1  3 7 12            10 and 2 are swapped */     struct Node *root = newNode(6);     root->left = newNode(10);     root->right = newNode(2);     root->left->left = newNode(1);     root->left->right = newNode(3);     root->right->right = newNode(12);     root->right->left = newNode(7);           // Inorder traversal of the Original Tree     cout <<"Inorder Traversal of the original tree \n";     printInorder(root);        correctBST(root);           // inorder traversal of the fixed tree     cout <<"\nInorder Traversal of the fixed tree \n";     printInorder(root);        return 0; } // THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002)

## Java

 import java.io.*; import java.util.ArrayList; import java.util.Collections;   class Node {     int data;     Node left;     Node right;     Node(int data)     {         this.data = data;         this.left = this.right = null;     } }   class GFG {     public static void storeInVector(Node root,                                      ArrayList vec)     {         if (root == null)             return;         storeInVector(root.left, vec);         vec.add(root.data);         storeInVector(root.right, vec);     }     public static void     correctBSTUtil(Node root, ArrayList vec,                    int[] index)     {         if (root == null)             return;         correctBSTUtil(root.left, vec, index);         root.data = vec.get(index[0]);         index[0]++;         correctBSTUtil(root.right, vec, index);     }       public static void correctBST(Node root)     {         // ArrayList to store the inorder traversal of         // given tree         ArrayList vec = new ArrayList();         storeInVector(root, vec);         Collections.sort(vec);         int[] index = { 0 };         correctBSTUtil(root, vec, index);     }       public static void printInorder(Node root)     {         if (root == null)             return;         printInorder(root.left);         System.out.print(root.data + " ");         printInorder(root.right);     }       public static void main(String[] args)     {         /*   6             / \            10  2           / \ / \          1  3 7 12           10 and 2 are swapped */         Node root = new Node(6);         root.left = new Node(10);         root.right = new Node(2);         root.left.left = new Node(1);         root.left.right = new Node(3);         root.right.right = new Node(12);         root.right.left = new Node(7);           // Inorder traversal of the Original Tree         System.out.println(             "Inorder Traversal of the original tree");         printInorder(root);           correctBST(root);           // inorder traversal of the fixed tree         System.out.println(             "\nInorder Traversal of the fixed tree");         printInorder(root);     } }

## Python3

 # Python3 program for the above approach   # Define the Node class to create new nodes     class Node:     def __init__(self, data):         self.data = data         self.left = None         self.right = None   # Define the function to create new nodes     def newNode(data):     return Node(data)   # Define the function to store the inorder traversal of the tree in a vector     def storeInVector(root, vec):     if root is None:         return     storeInVector(root.left, vec)     vec.append(root.data)     storeInVector(root.right, vec)   # Define the function to correct the BST     def correctBSTUtil(root, vec, index):     if root is None:         return index     index = correctBSTUtil(root.left, vec, index)     root.data = vec[index]     index += 1     index = correctBSTUtil(root.right, vec, index)     return index   # Define the main function to correct the BST     def correctBST(root):     # create a vector to store the inorder traversal of the given tree     vec = []     storeInVector(root, vec)     # sort the vector to obtain the correct inorder traversal of the BST     vec.sort()     index = 0     correctBSTUtil(root, vec, index)   # Define the function to print the inorder traversal of the tree     def printInorder(root):     if root is None:         return     printInorder(root.left)     print(root.data, end=' ')     printInorder(root.right)     # Define the main function to run the code if __name__ == '__main__':     # create the original tree     root = newNode(6)     root.left = newNode(10)     root.right = newNode(2)     root.left.left = newNode(1)     root.left.right = newNode(3)     root.right.right = newNode(12)     root.right.left = newNode(7)       # print the inorder traversal of the original tree     print("Inorder Traversal of the original tree")     printInorder(root)       # correct the BST     correctBST(root)       # print the inorder traversal of the fixed tree     print("\nInorder Traversal of the fixed tree")     printInorder(root)

## Javascript

 // JavaScript program for the above approach class Node{     constructor(data){         this.data = data;         this.left = null;         this.right = null;     } }   function newNode(data){     return new Node(data); }   function storeInVector(root, vec){     if(root == null) return;     storeInVector(root.left, vec);     vec.push(root.data);     storeInVector(root.right, vec); }   let index = 0; function correctBSTUtil(root, vec){     if(root == null) return;     correctBSTUtil(root.left, vec);     root.data = vec[index];     index++;     correctBSTUtil(root.right, vec); }   function correctBST(root){     // vector to store the inorder traveral of     // given binary tree     let vec = [];     storeInVector(root, vec);     vec.sort(function(a,b){return a-b});     correctBSTUtil(root, vec); }   function printInorder(root){     if(root == null) return;     printInorder(root.left);     console.log(root.data + " ");     printInorder(root.right); }   // driver program to test above functions /*   6     / \    10  2   / \ / \  1  3 7 12     10 and 2 are swapped */ let root = newNode(6); root.left = newNode(10); root.right = newNode(2); root.left.left = newNode(1); root.left.right = newNode(3); root.right.right = newNode(12); root.right.left = newNode(7);   // Inorder traversal of the original tree console.log("Inorder traversal of the original tree : "); printInorder(root);   correctBST(root);   // Inorder traversal of the fixed tree console.log("Inorder traversal of the fixed tree : "); printInorder(root);

## C#

 // C# Program for the above approach using System; using System.Collections.Generic;   public class Node {     public int data;     public Node left, right;     public Node(int data)     {         this.data = data;         this.left = this.right = null;     } }   public class GFG {     public static Node newNode(int data)     {         return new Node(data);     }     public static void storeInVector(Node root,                                      List vec)     {         if (root == null)             return;         storeInVector(root.left, vec);         vec.Add(root.data);         storeInVector(root.right, vec);     }       public static void     correctBSTUtil(Node root, List vec, ref int index)     {         if (root == null)             return;         correctBSTUtil(root.left, vec, ref index);         root.data = vec[index];         index++;         correctBSTUtil(root.right, vec, ref index);     }       public static void correctBST(Node root)     {         // List to store the inorder traversal of given tree         List vec = new List();         storeInVector(root, vec);         vec.Sort();         int index = 0;         correctBSTUtil(root, vec, ref index);     }       public static void printInorder(Node root)     {         if (root == null)             return;         printInorder(root.left);         Console.Write(root.data + " ");         printInorder(root.right);     }       public static void Main()     {         /*   6             / \            10  2           / \ / \          1  3 7 12           10 and 2 are swapped */         Node root = newNode(6);         root.left = newNode(10);         root.right = newNode(2);         root.left.left = newNode(1);         root.left.right = newNode(3);         root.right.right = newNode(12);         root.right.left = newNode(7);           // Inorder traversal of the Original Tree         Console.Write(             "Inorder Traversal of the original tree \n");         printInorder(root);           correctBST(root);           // inorder traversal of the fixed tree         Console.Write(             "\nInorder Traversal of the fixed tree \n");         printInorder(root);     } }

Output

Inorder Traversal of the original tree
1 10 3 6 7 2 12
Inorder Traversal of the fixed tree
1 2 3 6 7 10 12

Time complexity: O(N * logN)
Auxiliary Space: O(N).

We can solve this in O(n) time and with a single traversal of the given BST

## Two nodes of a BST are swapped, correct the BST using recursion:

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

Illustration:

1. The swapped nodes are not adjacent in the in-order traversal of the BST.

For example, Nodes 5 and 25 are swapped in {3 5 7 8 10 15 20 25}.
The inorder traversal of the given tree is 3 25 7 8 10 15 20 5

Observe carefully, during inorder traversal, find node 7 is smaller than the previously visited node 25. Here save the context of node 25 (previous node). Again, find that node 5 is smaller than the previous node 20. This time, save the context of node 5 (the current node ). Finally, swap the two node’s values.

2. The swapped nodes are adjacent in the inorder traversal of BST.

For example, Nodes 7 and 8 are swapped in {3 5 7 8 10 15 20 25}.
The inorder traversal of the given tree is 3 5 8 7 10 15 20 25

Here only one point exists where a node value is smaller than the previous node value. e.g. node 7 is smaller than node 8.

Follow the below steps to implement the idea:

• Initialize pointers prev, first, middle, and last as Null pointers.
• Traverse the Binary search tree in in-order form
• Make a recursive call for root -> left.
• If *prev != null and root -> data < (*prev)->data) then
• If first = Null then set first = prev and middle = root.
• Else last = root.
• Make a recursive call for root -> right.
• Store the current node as prev.
• If last != Null swap last and first pointer.
• Else swap first and middle pointer

Below is the implementation of the above approach.

## C++

 // Two nodes in the BST's swapped, correct the BST. #include using namespace std;   /* A binary tree node has data, pointer to left child    and a pointer to right child */ struct node {     int data;     struct node *left, *right; };   // A utility function to swap two integers void swap( int* a, int* b ) {     int t = *a;     *a = *b;     *b = t; }   /* Helper function that allocates a new node with the    given data and NULL left and right pointers. */ struct node* newNode(int data) {     struct node* node = (struct node *)malloc(sizeof(struct node));     node->data = data;     node->left = NULL;     node->right = NULL;     return(node); }   // This function does inorder traversal to find out the two swapped nodes. // It sets three pointers, first, middle and last.  If the swapped nodes are // adjacent to each other, then first and middle contain the resultant nodes // Else, first and last contain the resultant nodes void correctBSTUtil( struct node* root, struct node** first,                      struct node** middle, struct node** last,                      struct node** prev ) {     if( root )     {         // Recur for the left subtree         correctBSTUtil( root->left, first, middle, last, prev );           // If this node is smaller than the previous node, it's violating         // the BST rule.         if (*prev && root->data < (*prev)->data)         {                         // If this is first violation, mark these two nodes as             // 'first' and 'middle'             if ( !*first )             {                 *first = *prev;                 *middle = root;             }               // If this is second violation, mark this node as last             else                 *last = root;         }           // Mark this node as previous         *prev = root;           // Recur for the right subtree         correctBSTUtil( root->right, first, middle, last, prev );     } }   // A function to fix a given BST where two nodes are swapped.  This // function uses correctBSTUtil() to find out two nodes and swaps the // nodes to fix the BST void correctBST( struct node* root ) {         // Initialize pointers needed for correctBSTUtil()     struct node *first, *middle, *last, *prev;     first = middle = last = prev = NULL;       // Set the pointers to find out two nodes     correctBSTUtil( root, &first, &middle, &last, &prev );       // Fix (or correct) the tree     if( first && last )         swap( &(first->data), &(last->data) );     else if( first && middle ) // Adjacent nodes swapped         swap( &(first->data), &(middle->data) );       // else nodes have not been swapped, passed tree is really BST. }   /* A utility function to print Inorder traversal */ void printInorder(struct node* node) {     if (node == NULL)         return;     printInorder(node->left);     cout <<"  "<< node->data;     printInorder(node->right); }   /* Driver program to test above functions*/ int main() {     /*   6         /  \        10    2       / \   / \      1   3 7  12      10 and 2 are swapped     */       struct node *root = newNode(6);     root->left        = newNode(10);     root->right       = newNode(2);     root->left->left  = newNode(1);     root->left->right = newNode(3);     root->right->right = newNode(12);     root->right->left = newNode(7);       cout <<"Inorder Traversal of the original tree \n";     printInorder(root);       correctBST(root);       cout <<"\nInorder Traversal of the fixed tree \n";     printInorder(root);       return 0; }   // This code is contributed by shivanisinghss2110

## C

 // Two nodes in the BST's swapped, correct the BST. #include #include   /* A binary tree node has data, pointer to left child    and a pointer to right child */ struct node {     int data;     struct node *left, *right; };   // A utility function to swap two integers void swap( int* a, int* b ) {     int t = *a;     *a = *b;     *b = t; }   /* Helper function that allocates a new node with the    given data and NULL left and right pointers. */ struct node* newNode(int data) {     struct node* node = (struct node *)malloc(sizeof(struct node));     node->data = data;     node->left = NULL;     node->right = NULL;     return(node); }   // This function does inorder traversal to find out the two swapped nodes. // It sets three pointers, first, middle and last.  If the swapped nodes are // adjacent to each other, then first and middle contain the resultant nodes // Else, first and last contain the resultant nodes void correctBSTUtil( struct node* root, struct node** first,                      struct node** middle, struct node** last,                      struct node** prev ) {     if( root )     {         // Recur for the left subtree         correctBSTUtil( root->left, first, middle, last, prev );           // If this node is smaller than the previous node, it's violating         // the BST rule.         if (*prev && root->data < (*prev)->data)         {             // If this is first violation, mark these two nodes as             // 'first' and 'middle'             if ( !*first )             {                 *first = *prev;                 *middle = root;             }               // If this is second violation, mark this node as last             else                 *last = root;         }           // Mark this node as previous         *prev = root;           // Recur for the right subtree         correctBSTUtil( root->right, first, middle, last, prev );     } }   // A function to fix a given BST where two nodes are swapped.  This // function uses correctBSTUtil() to find out two nodes and swaps the // nodes to fix the BST void correctBST( struct node* root ) {     // Initialize pointers needed for correctBSTUtil()     struct node *first, *middle, *last, *prev;     first = middle = last = prev = NULL;       // Set the pointers to find out two nodes     correctBSTUtil( root, &first, &middle, &last, &prev );       // Fix (or correct) the tree     if( first && last )         swap( &(first->data), &(last->data) );     else if( first && middle ) // Adjacent nodes swapped         swap( &(first->data), &(middle->data) );       // else nodes have not been swapped, passed tree is really BST. }   /* A utility function to print Inorder traversal */ void printInorder(struct node* node) {     if (node == NULL)         return;     printInorder(node->left);     printf("%d ", node->data);     printInorder(node->right); }   /* Driver program to test above functions*/ int main() {     /*   6         /  \        10    2       / \   / \      1   3 7  12      10 and 2 are swapped     */       struct node *root = newNode(6);     root->left        = newNode(10);     root->right       = newNode(2);     root->left->left  = newNode(1);     root->left->right = newNode(3);     root->right->right = newNode(12);     root->right->left = newNode(7);       printf("Inorder Traversal of the original tree \n");     printInorder(root);       correctBST(root);       printf("\nInorder Traversal of the fixed tree \n");     printInorder(root);       return 0; }

## Java

 // Java program to correct the BST // if two nodes are swapped import java.util.*; import java.lang.*; import java.io.*;   class Node {       int data;     Node left, right;       Node(int d) {         data = d;         left = right = null;     } }   class BinaryTree {     Node first, middle, last, prev;           // This function does inorder traversal     // to find out the two swapped nodes.     // It sets three pointers, first, middle     // and last. If the swapped nodes are     // adjacent to each other, then first     // and middle contain the resultant nodes     // Else, first and last contain the     // resultant nodes     void correctBSTUtil( Node root)     {         if( root != null )         {             // Recur for the left subtree             correctBSTUtil( root.left);               // If this node is smaller than             // the previous node, it's             // violating the BST rule.             if (prev != null && root.data <                                 prev.data)             {                 // If this is first violation,                 // mark these two nodes as                 // 'first' and 'middle'                 if (first == null)                 {                     first = prev;                     middle = root;                 }                   // If this is second violation,                 // mark this node as last                 else                     last = root;             }               // Mark this node as previous             prev = root;               // Recur for the right subtree             correctBSTUtil( root.right);         }     }       // A function to fix a given BST where     // two nodes are swapped. This function     // uses correctBSTUtil() to find out     // two nodes and swaps the nodes to     // fix the BST     void correctBST( Node root )     {         // Initialize pointers needed         // for correctBSTUtil()         first = middle = last = prev = null;           // Set the pointers to find out         // two nodes         correctBSTUtil( root );           // Fix (or correct) the tree         if( first != null && last != null )         {             int temp = first.data;             first.data = last.data;             last.data = temp;         }         // Adjacent nodes swapped         else if( first != null && middle !=                                     null )         {             int temp = first.data;             first.data = middle.data;             middle.data = temp;         }           // else nodes have not been swapped,         // passed tree is really BST.     }       /* A utility function to print      Inorder traversal */     void printInorder(Node node)     {         if (node == null)             return;         printInorder(node.left);         System.out.print(" " + node.data);         printInorder(node.right);     }         // Driver program to test above functions     public static void main (String[] args)     {         /*   6             / \            10  2           / \ / \          1  3 7 12                   10 and 2 are swapped         */           Node root = new Node(6);         root.left = new Node(10);         root.right = new Node(2);         root.left.left = new Node(1);         root.left.right = new Node(3);         root.right.right = new Node(12);         root.right.left = new Node(7);           System.out.println("Inorder Traversal"+                         " of the original tree");         BinaryTree tree = new BinaryTree();         tree.printInorder(root);           tree.correctBST(root);           System.out.println("\nInorder Traversal"+                           " of the fixed tree");         tree.printInorder(root);     } } // This code is contributed by Chhavi

## Python3

 # Python3 program to correct the BST  # if two nodes are swapped class Node:           # Constructor to create a new node     def __init__(self, data):                   self.key = data         self.left = None         self.right = None   # Utility function to track the nodes # that we have to swap def correctBstUtil(root, first, middle,                    last, prev):                              if(root):                   # Recur for the left sub tree         correctBstUtil(root.left, first,                        middle, last, prev)                                  # If this is the first violation, mark these         # two nodes as 'first and 'middle'         if(prev[0] and root.key < prev[0].key):             if(not first[0]):                 first[0] = prev[0]                 middle[0] = root             else:                                   # If this is the second violation,                 # mark this node as last                 last[0] = root                           prev[0] = root                   # Recur for the right subtree         correctBstUtil(root.right, first,                        middle, last, prev)       # A function to fix a given BST where # two nodes are swapped. This function # uses correctBSTUtil() to find out two # nodes and swaps the nodes to fix the BST def correctBst(root):           # Followed four lines just for forming     # an array with only index 0 filled     # with None and we will update it accordingly.     # we made it null so that we can fill     # node data in them.     first = [None]     middle = [None]     last = [None]     prev = [None]           # Setting arrays (having zero index only)     # for capturing the required node     correctBstUtil(root, first, middle,                    last, prev)       # Fixing the two nodes     if(first[0] and last[0]):                   # Swapping for first and last key values         first[0].key, last[0].key = (last[0].key,                                     first[0].key)       elif(first[0] and middle[0]):               # Swapping for first and middle key values         first[0].key, middle[0].key = (middle[0].key,                                         first[0].key)           # else tree will be fine   # Function to print inorder # traversal of tree def PrintInorder(root):           if(root):         PrintInorder(root.left)         print(root.key, end = " ")         PrintInorder(root.right)               else:         return   # Driver code   #      6 #     /   \ #   10    2 #  / \   / \ # 1   3 7   12   # Following 7 lines are for tree formation root = Node(6) root.left = Node(10) root.right = Node(2) root.left.left = Node(1) root.left.right = Node(3) root.right.left = Node(7) root.right.right = Node(12)   # Printing inorder traversal of normal tree print("inorder traversal of normal tree") PrintInorder(root) print("")   # Function call to do the task correctBst(root)   # Printing inorder for corrected Bst tree print("") print("inorder for corrected BST")   PrintInorder(root)   # This code is contributed by rajutkarshai

## C#

 // C# program to correct the BST // if two nodes are swapped using System; class Node{   public int data; public Node left, right; public Node(int d) {   data = d;   left = right = null; } }   class BinaryTree {   Node first, middle,        last, prev;   // This function does inorder traversal // to find out the two swapped nodes. // It sets three pointers, first, middle // and last. If the swapped nodes are // adjacent to each other, then first // and middle contain the resultant nodes // Else, first and last contain the // resultant nodes void correctBSTUtil( Node root) {   if( root != null )   {     // Recur for the     // left subtree     correctBSTUtil(root.left);       // If this node is smaller than     // the previous node, it's     // violating the BST rule.     if (prev != null && root.data <         prev.data)     {       // If this is first violation,       // mark these two nodes as       // 'first' and 'middle'       if (first == null)       {         first = prev;         middle = root;       }         // If this is second violation,       // mark this node as last       else         last = root;     }       // Mark this node     // as previous     prev = root;       // Recur for the     // right subtree     correctBSTUtil(root.right);   } }   // A function to fix a given BST where // two nodes are swapped. This function // uses correctBSTUtil() to find out // two nodes and swaps the nodes to // fix the BST void correctBST( Node root ) {   // Initialize pointers needed   // for correctBSTUtil()   first = middle = last =           prev = null;     // Set the pointers to   // find out two nodes   correctBSTUtil(root);     // Fix (or correct)   // the tree   if(first != null &&      last != null)   {     int temp = first.data;     first.data = last.data;     last.data = temp;   }       // Adjacent nodes swapped   else if(first != null &&           middle != null)   {     int temp = first.data;     first.data = middle.data;     middle.data = temp;   }     // else nodes have not been   // swapped, passed tree is   // really BST. }   // A utility function to print // Inorder traversal void printInorder(Node node) {   if (node == null)     return;   printInorder(node.left);   Console.Write(" " + node.data);   printInorder(node.right); }   // Driver code public static void Main(String[] args) {   /*         6             / \            10  2           / \ / \          1  3 7 12           10 and 2 are swapped         */     Node root = new Node(6);   root.left = new Node(10);   root.right = new Node(2);   root.left.left = new Node(1);   root.left.right = new Node(3);   root.right.right = new Node(12);   root.right.left = new Node(7);     Console.WriteLine("Inorder Traversal" +                     " of the original tree");   BinaryTree tree = new BinaryTree();   tree.printInorder(root);   tree.correctBST(root);   Console.WriteLine("\nInorder Traversal" +                     " of the fixed tree");   tree.printInorder(root); } }   // This code is contributed by gauravrajput1

## Javascript



Output

Inorder Traversal of the original tree
1  10  3  6  7  2  12
Inorder Traversal of the fixed tree
1  2  3  6  7  10  12

Time Complexity: O(N)
Auxiliary Space: O(N) for recursive call stack

My Personal Notes arrow_drop_up