[Naive Approach] Using Inorder Traversal and Sorting - O(n * log n) Time and O(n) Space
The idea is to use the property of BST: an inorder traversal of a valid BST gives elements in sorted order. First, traverse the tree and store all node values in an array. Since exactly two nodes are swapped so that array will not be fully sorted. Sort the array to get the correct order of elements. Finally, traverse the tree again in inorder fashion, and replace each node’s value with the corresponding value from the sorted array. This restores the original BST structure while maintaining all other nodes in place.
C++
//Driver Code Starts#include<iostream>#include<vector>#include<queue>#include<algorithm>usingnamespacestd;// Node structureclassNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// Calculate HeightintgetHeight(Node*root,inth){if(root==nullptr)returnh-1;returnmax(getHeight(root->left,h+1),getHeight(root->right,h+1));}// Print Level OrdervoidlevelOrder(Node*root){queue<pair<Node*,int>>q;q.push({root,0});intlastLevel=0;// function to get the height of treeintheight=getHeight(root,0);// printing the level order of treewhile(!q.empty()){autotop=q.front();q.pop();Node*node=top.first;intlvl=top.second;if(lvl>lastLevel){cout<<"";lastLevel=lvl;}// all levels are printedif(lvl>height)break;if(node->data!=-1)cout<<node->data<<" ";// printing null nodeelsecout<<"N ";// null node has no childrenif(node->data==-1)continue;if(node->left==nullptr)q.push({newNode(-1),lvl+1});elseq.push({node->left,lvl+1});if(node->right==nullptr)q.push({newNode(-1),lvl+1});elseq.push({node->right,lvl+1});}}//Driver Code Ends// Function to store the inorder traversal voidfindInorder(Node*curr,vector<int>&inorder){if(curr==nullptr)return;findInorder(curr->left,inorder);inorder.push_back(curr->data);findInorder(curr->right,inorder);}// Recursive function to correct the BST by replacing// node values with sorted valuesvoidcorrectBSTUtil(Node*root,vector<int>&inorder,int&index){if(root==nullptr)return;correctBSTUtil(root->left,inorder,index);root->data=inorder[index];index++;correctBSTUtil(root->right,inorder,index);}// Function to fix the given BST voidcorrectBST(Node*root){vector<int>inorder;findInorder(root,inorder);sort(inorder.begin(),inorder.end());intindex=0;correctBSTUtil(root,inorder,index);}//Driver Code Startsintmain(){// Constructing the tree with swapped nodes// 6// / \ // 10 2// / \ / \ // 1 3 7 12Node*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);correctBST(root);levelOrder(root);return0;}//Driver Code Ends
Java
//Driver Code Startsimportjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// calculate HeightstaticintgetHeight(Noderoot,inth){if(root==null)returnh-1;returnMath.max(getHeight(root.left,h+1),getHeight(root.right,h+1));}// calculate Height// Print Level OrderstaticvoidlevelOrder(Noderoot){Queue<List<Object>>queue=newLinkedList<>();queue.offer(List.of(root,0));intlastLevel=0;// function to get the height of treeintheight=getHeight(root,0);// printing the level order of treewhile(!queue.isEmpty()){List<Object>top=queue.poll();Nodenode=(Node)top.get(0);intlvl=(int)top.get(1);if(lvl>lastLevel){System.out.println();lastLevel=lvl;}// all levels are printedif(lvl>height)break;// printing null nodeSystem.out.print((node.data==-1?"N":node.data)+" ");// null node has no childrenif(node.data==-1)continue;if(node.left==null)queue.offer(List.of(newNode(-1),lvl+1));elsequeue.offer(List.of(node.left,lvl+1));if(node.right==null)queue.offer(List.of(newNode(-1),lvl+1));elsequeue.offer(List.of(node.right,lvl+1));}}//Driver Code Ends// Function to store the inorder traversal staticvoidfindInorder(Nodecurr,ArrayList<Integer>inorder){if(curr==null)return;findInorder(curr.left,inorder);inorder.add(curr.data);findInorder(curr.right,inorder);}// Recursive function to correct the BST by replacing// node values with sorted valuesstaticvoidcorrectBSTUtil(Noderoot,ArrayList<Integer>inorder,int[]index){if(root==null)return;correctBSTUtil(root.left,inorder,index);root.data=inorder.get(index[0]);index[0]++;correctBSTUtil(root.right,inorder,index);}// Function to fix the given BST staticvoidcorrectBST(Noderoot){ArrayList<Integer>inorder=newArrayList<>();findInorder(root,inorder);Collections.sort(inorder);int[]index={0};correctBSTUtil(root,inorder,index);}//Driver Code Startspublicstaticvoidmain(String[]args){// Constructing the tree with swapped nodes// 6// / \// 10 2// / \ / \// 1 3 7 12// Here, 10 and 2 are swappedNoderoot=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);correctBST(root);levelOrder(root);}}//Driver Code Ends
Python
#Driver Code StartsfromcollectionsimportdequeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# calculate HeightdefgetHeight(root,h):ifrootisNone:returnh-1returnmax(getHeight(root.left,h+1),getHeight(root.right,h+1))# Print Level OrderdeflevelOrder(root):queue=deque([[root,0]])lastLevel=0# function to get the height of treeheight=getHeight(root,0)# printing the level order of treewhilequeue:node,lvl=queue.popleft()iflvl>lastLevel:print()lastLevel=lvl# all levels are printediflvl>height:break# printing null nodeprint("N"ifnode.data==-1elsenode.data,end=" ")# null node has no childrenifnode.data==-1:continueifnode.leftisNone:queue.append([Node(-1),lvl+1])else:queue.append([node.left,lvl+1])ifnode.rightisNone:queue.append([Node(-1),lvl+1])else:queue.append([node.right,lvl+1])#Driver Code Ends# Function to store the inorder# traversal deffindInorder(curr,inorder):ifcurrisNone:returnfindInorder(curr.left,inorder)inorder.append(curr.data)findInorder(curr.right,inorder)# Recursive function to correct the BST by replacing# node values with sorted valuesdefcorrectBSTUtil(root,inorder,index):ifrootisNone:returncorrectBSTUtil(root.left,inorder,index)root.data=inorder[index[0]]index[0]+=1correctBSTUtil(root.right,inorder,index)# Function to fix the given BST defcorrectBST(root):inorder=[]findInorder(root,inorder)inorder.sort()index=[0]correctBSTUtil(root,inorder,index)#Driver Code Startsif__name__=="__main__":# Constructing the tree with swapped nodes# 6# / \# 10 2# / \ / \# 1 3 7 12root=Node(6)root.left=Node(10)root.right=Node(2)root.left.left=Node(1)root.left.right=Node(3)root.right.right=Node(12)root.right.left=Node(7)correctBST(root)levelOrder(root)#Driver Code Ends
C#
//Driver Code StartsusingSystem;usingSystem.Collections.Generic;// Node structurepublicclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=right=null;}}publicclassGFG{//Calculate HeightstaticintgetHeight(Noderoot,inth){if(root==null)returnh-1;returnMath.Max(getHeight(root.left,h+1),getHeight(root.right,h+1));}// Print Level OrderstaticvoidlevelOrder(Noderoot){if(root==null)return;Queue<(Node,int)>queue=newQueue<(Node,int)>();queue.Enqueue((root,0));intlastLevel=0;intheight=getHeight(root,0);while(queue.Count>0){var(node,lvl)=queue.Dequeue();if(lvl>lastLevel){Console.WriteLine();lastLevel=lvl;}// Stop printing if all levels are doneif(lvl>height)break;// print null nodeConsole.Write((node.data==-1?"N":node.data.ToString())+" ");// null node has no childrenif(node.data==-1)continue;if(node.left==null)queue.Enqueue((newNode(-1),lvl+1));elsequeue.Enqueue((node.left,lvl+1));if(node.right==null)queue.Enqueue((newNode(-1),lvl+1));elsequeue.Enqueue((node.right,lvl+1));}}//Driver Code Ends// Function to store the inorder traversalstaticvoidfindInorder(Nodecurr,List<int>inorder){if(curr==null)return;findInorder(curr.left,inorder);inorder.Add(curr.data);findInorder(curr.right,inorder);}// Recursive function to correct the BST by replacing// node values with sorted valuesstaticvoidcorrectBSTUtil(Noderoot,List<int>inorder,refintindex){if(root==null)return;correctBSTUtil(root.left,inorder,refindex);root.data=inorder[index];index++;correctBSTUtil(root.right,inorder,refindex);}// Function to fix the given BSTstaticvoidcorrectBST(Noderoot){List<int>inorder=newList<int>();findInorder(root,inorder);// Sort inorder array since two nodes are swappedinorder.Sort();intindex=0;correctBSTUtil(root,inorder,refindex);}//Driver Code StartsstaticvoidMain(){// Constructing the tree with swapped nodes// 6// / \// 10 2// / \ / \// 1 3 7 12Noderoot=newNode(6);root.left=newNode(10);root.right=newNode(2);root.left.left=newNode(1);root.left.right=newNode(3);root.right.left=newNode(7);root.right.right=newNode(12);correctBST(root);levelOrder(root);}}//Driver Code Ends
JavaScript
//Driver Code Starts// Node structureclassNode{constructor(x){this.data=x;this.left=this.right=null;}}// Queue node for custom queue implementationclassQNode{constructor(data){this.data=data;this.next=null;}}// Custom Queue implementationclassQueue{constructor(){this.front=null;this.rear=null;}isEmpty(){returnthis.front===null;}enqueue(x){letnewNode=newQNode(x);if(this.rear===null){this.front=this.rear=newNode;return;}this.rear.next=newNode;this.rear=newNode;}dequeue(){if(this.front===null)returnnull;lettemp=this.front;this.front=this.front.next;if(this.front===null)this.rear=null;returntemp.data;}}// Calculate HeightfunctiongetHeight(root,h){if(root===null)returnh-1;returnMath.max(getHeight(root.left,h+1),getHeight(root.right,h+1));}// Print Level OrderfunctionlevelOrder(root){letqueue=newQueue();queue.enqueue([root,0]);letlastLevel=0;letheight=getHeight(root,0);while(!queue.isEmpty()){let[node,lvl]=queue.dequeue();if(lvl>lastLevel){console.log("");lastLevel=lvl;}// all levels are printedif(lvl>height)break;// print null nodeprocess.stdout.write((node.data===-1?"N":node.data)+" ");// null node has no childrenif(node.data===-1)continue;if(node.left===null)queue.enqueue([newNode(-1),lvl+1]);elsequeue.enqueue([node.left,lvl+1]);if(node.right===null)queue.enqueue([newNode(-1),lvl+1]);elsequeue.enqueue([node.right,lvl+1]);}}//Driver Code Ends// Function to store the inorder traversalfunctionfindInorder(curr,inorder){if(curr==null)return;findInorder(curr.left,inorder);inorder.push(curr.data);findInorder(curr.right,inorder);}// Recursive function to correct the BST by replacing// node values with sorted valuesfunctioncorrectBSTUtil(root,inorder,index){if(root==null)return;correctBSTUtil(root.left,inorder,index);root.data=inorder[index.value];index.value++;correctBSTUtil(root.right,inorder,index);}// Function to fix the given BSTfunctioncorrectBST(root){letinorder=[];findInorder(root,inorder);inorder.sort((a,b)=>a-b);letindex={value:0};correctBSTUtil(root,inorder,index);}//Driver Code Starts// Driver Code// Constructing the tree with swapped nodes// 6// / \// 10 2// / \ / \// 1 3 7 12letroot=newNode(6);root.left=newNode(10);root.right=newNode(2);root.left.left=newNode(1);root.left.right=newNode(3);root.right.left=newNode(7);root.right.right=newNode(12);correctBST(root);levelOrder(root);//Driver Code Ends
Output
6
2 10
1 3 7 12
[Expected Approach] Using One Traversal - O(n) Time and O(h) Space
In a BST, two nodes are swapped so, there are two possible scenarios:
Swapped nodes are adjacent in inorder traversal:
In this case, the inorder traversal of the BST will show only one violation (a pair of nodes where the previous node’s value is greater than the current node’s value).
To track this, we use three pointers: first, middle, and last, along with a prev pointer.
When the violation is detected, update first to point to the previous node and middle to the current node.
Since there is only one violation, swapping first and middle will restore the BST.
Swapped nodes are not adjacent in inorder traversal:
Here, the inorder traversal will show two violations.
During traversal, the first violation sets first and middle. The second violation updates the last pointer to the current node.
Finally, swapping the values of first and last restores the BST correctly.
C++
//Driver Code Starts#include<iostream>#include<queue>#include<algorithm>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intval){data=val;left=nullptr;right=nullptr;}};// Function to get height of treeintgetHeight(Node*root,inth){if(root==nullptr)returnh-1;returnmax(getHeight(root->left,h+1),getHeight(root->right,h+1));}// Print Level OrdervoidlevelOrder(Node*root){if(!root){cout<<"N";return;}queue<pair<Node*,int>>q;q.push({root,0});intlastLevel=0;intheight=getHeight(root,0);while(!q.empty()){autotop=q.front();q.pop();Node*node=top.first;intlvl=top.second;if(lvl>lastLevel){cout<<"";lastLevel=lvl;}if(lvl>height)break;// printing null nodeif(node->data!=-1)cout<<node->data<<" ";elsecout<<"N ";// Null nodes have no childrenif(node->data==-1)continue;if(node->left==nullptr)q.push({newNode(-1),lvl+1});elseq.push({node->left,lvl+1});if(node->right==nullptr)q.push({newNode(-1),lvl+1});elseq.push({node->right,lvl+1});}}//Driver Code Ends// Recursive Function for inorder traversal// to find out the two swapped nodesvoidcorrectBSTUtil(Node*root,Node*&first,Node*&middle,Node*&last,Node*&prev){if(root==nullptr)return;// Recur for left subtreecorrectBSTUtil(root->left,first,middle,last,prev);// Detect violation of BST propertyif(prev&&root->data<prev->data){// First violationif(!first){first=prev;middle=root;}// Second violationelse{last=root;}}// Update previous nodeprev=root;// Recur for right subtreecorrectBSTUtil(root->right,first,middle,last,prev);}// Function to fix the BSTvoidcorrectBST(Node*root){Node*first=nullptr,*middle=nullptr,*last=nullptr,*prev=nullptr;correctBSTUtil(root,first,middle,last,prev);if(first&&last)swap(first->data,last->data);elseif(first&&middle)swap(first->data,middle->data);}//Driver Code Startsintmain(){// Constructing the tree with swapped nodes// 6// / \ // 10 2// / \ / \ // 1 3 7 12Node*root=newNode(6);root->left=newNode(10);root->right=newNode(2);root->left->left=newNode(1);root->left->right=newNode(3);root->right->left=newNode(7);root->right->right=newNode(12);correctBST(root);levelOrder(root);return0;}//Driver Code Ends
Java
//Driver Code Startsimportjava.util.LinkedList;importjava.util.Queue;importjava.util.List;importjava.util.ArrayList;importjava.util.HashMap;importjava.util.Map;classNode{intdata;Nodeleft,right;Node(intval){data=val;left=right=null;}}classMain{// Function to get the height of the treestaticintgetHeight(Noderoot,inth){if(root==null)returnh-1;returnMath.max(getHeight(root.left,h+1),getHeight(root.right,h+1));}// Print Level OrderstaticvoidlevelOrder(Noderoot){Queue<List<Object>>queue=newLinkedList<>();queue.offer(List.of(root,0));intlastLevel=0;intheight=getHeight(root,0);while(!queue.isEmpty()){List<Object>top=queue.poll();Nodenode=(Node)top.get(0);intlvl=(int)top.get(1);if(lvl>lastLevel){System.out.println();lastLevel=lvl;}if(lvl>height)break;// printing null nodeSystem.out.print((node.data==-1?"N":node.data)+" ");// null node has no childrenif(node.data==-1)continue;if(node.left==null)queue.offer(List.of(newNode(-1),lvl+1));elsequeue.offer(List.of(node.left,lvl+1));if(node.right==null)queue.offer(List.of(newNode(-1),lvl+1));elsequeue.offer(List.of(node.right,lvl+1));}}//Driver Code EndsstaticNodefirst,middle,last,prev;// Recursive Function for inorder traversal// to find out the two swapped nodesstaticvoidcorrectBSTUtil(Noderoot){if(root==null)return;// Recur for the left subtreecorrectBSTUtil(root.left);//first violationif(prev!=null&&root.data<prev.data){if(first==null){first=prev;middle=root;}// second violation,else{last=root;}}// Mark this node as previousprev=root;// Recur for the right subtreecorrectBSTUtil(root.right);}// Function to fix the BSTstaticvoidcorrectBST(Noderoot){first=middle=last=prev=null;correctBSTUtil(root);// Fix (or correct) the treeif(first!=null&&last!=null)swap(first,last);elseif(first!=null&&middle!=null)swap(first,middle);}staticvoidswap(Nodea,Nodeb){inttemp=a.data;a.data=b.data;b.data=temp;}//Driver Code Startspublicstaticvoidmain(String[]args){// Constructing the tree with swapped nodes// 6// / \// 10 2// / \ / \// 1 3 7 12// Here, 10 and 2 are swappedNoderoot=newNode(6);root.left=newNode(10);root.right=newNode(2);root.left.left=newNode(1);root.left.right=newNode(3);root.right.left=newNode(7);root.right.right=newNode(12);correctBST(root);levelOrder(root);}}//Driver Code Ends
Python
#Driver Code StartsclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=None# Function to get the height of the treedefgetHeight(root,h):ifrootisNone:returnh-1returnmax(getHeight(root.left,h+1),getHeight(root.right,h+1))# Print level OrderdeflevelOrder(root):fromcollectionsimportdequequeue=deque()queue.append((root,0))lastLevel=0height=getHeight(root,0)whilequeue:node,lvl=queue.popleft()iflvl>lastLevel:print()lastLevel=lvliflvl>height:break# printing null nodeprint("N"ifnode.data==-1elsenode.data,end=" ")# null node has no childrenifnode.data==-1:continueifnode.leftisNone:queue.append((Node(-1),lvl+1))else:queue.append((node.left,lvl+1))ifnode.rightisNone:queue.append((Node(-1),lvl+1))else:queue.append((node.right,lvl+1))#Driver Code Ends# Global pointersfirst=Nonemiddle=Nonelast=Noneprev=None# Recursive Function for inorder traversal# to find out the two swapped nodesdefcorrectBSTUtil(root):globalfirst,middle,last,previfrootisNone:return# Recur for the left subtreecorrectBSTUtil(root.left)ifprevandroot.data<prev.data:# first violationiffirstisNone:first=prevmiddle=root# second violationelse:last=root# Mark this node as previousprev=root# Recur for the right subtreecorrectBSTUtil(root.right)# Function to fix the given BSTdefcorrectBST(root):globalfirst,middle,last,prevfirst=middle=last=prev=NonecorrectBSTUtil(root)iffirstandlast:swap(first,last)eliffirstandmiddle:swap(first,middle)defswap(a,b):temp=a.dataa.data=b.datab.data=temp#Driver Code Startsif__name__=="__main__":# Constructing the tree with swapped nodes# 6# / \# 10 2# / \ / \# 1 3 7 12root=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)correctBST(root)levelOrder(root)#Driver Code Ends
C#
//Driver Code StartsusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intval){data=val;left=right=null;}}classSolution{// Function to get the height of the treestaticintgetHeight(Noderoot,inth){if(root==null)returnh-1;returnMath.Max(getHeight(root.left,h+1),getHeight(root.right,h+1));}// Print Level OrderstaticvoidlevelOrder(Noderoot){if(root==null)return;Queue<(Node,int)>queue=newQueue<(Node,int)>();queue.Enqueue((root,0));intlastLevel=0;intheight=getHeight(root,0);while(queue.Count>0){var(node,lvl)=queue.Dequeue();if(lvl>lastLevel){Console.WriteLine();lastLevel=lvl;}if(lvl>height)break;// printing null nodeConsole.Write((node.data==-1?"N":node.data.ToString())+" ");// null node has no childrenif(node.data==-1)continue;if(node.left==null)queue.Enqueue((newNode(-1),lvl+1));elsequeue.Enqueue((node.left,lvl+1));if(node.right==null)queue.Enqueue((newNode(-1),lvl+1));elsequeue.Enqueue((node.right,lvl+1));}}//Driver Code EndsstaticNodefirst=null,middle=null,last=null,prev=null;// Recursive Function for inorder traversal// to find out the two swapped nodesstaticvoidcorrectBSTUtil(Noderoot){if(root==null)return;correctBSTUtil(root.left);if(prev!=null&&root.data<prev.data){// first violationif(first==null){first=prev;middle=root;}// second violation,else{last=root;}}// Mark this node as previousprev=root;// Recur for the right subtreecorrectBSTUtil(root.right);}// Function to fix the given BSTstaticvoidcorrectBST(Noderoot){first=middle=last=prev=null;correctBSTUtil(root);if(first!=null&&last!=null)Swap(first,last);elseif(first!=null&&middle!=null)Swap(first,middle);}staticvoidSwap(Nodea,Nodeb){inttemp=a.data;a.data=b.data;b.data=temp;}//Driver Code StartsstaticvoidMain(){// Constructing the tree with swapped nodes// 6// / \// 10 2// / \ / \// 1 3 7 12Noderoot=newNode(6);root.left=newNode(10);root.right=newNode(2);root.left.left=newNode(1);root.left.right=newNode(3);root.right.left=newNode(7);root.right.right=newNode(12);correctBST(root);levelOrder(root);}}//Driver Code Ends
JavaScript
//Driver Code StartsclassNode{constructor(val){this.data=val;this.left=null;this.right=null;}}// Queue implementation for Node*classQNode{constructor(data){this.data=data;this.next=null;}}classQueue{constructor(){this.front=null;this.rear=null;}isEmpty(){returnthis.front===null;}enqueue(x){letnewNode=newQNode(x);if(this.rear===null){this.front=this.rear=newNode;return;}this.rear.next=newNode;this.rear=newNode;}dequeue(){if(this.front===null)returnnull;lettemp=this.front;this.front=this.front.next;if(this.front===null)this.rear=null;returntemp.data;}}// Function to get the height of the treefunctiongetHeight(root,h){if(root===null)returnh-1;returnMath.max(getHeight(root.left,h+1),getHeight(root.right,h+1));}// Print Level OrderfunctionlevelOrder(root){letqueue=[];queue.push([root,0]);letlastLevel=0;letheight=getHeight(root,0);while(queue.length>0){let[node,lvl]=queue.shift();if(lvl>lastLevel){console.log("");lastLevel=lvl;}if(lvl>height)break;// printing null nodeprocess.stdout.write((node.data===-1?"N":node.data)+" ");// null node has no childrenif(node.data===-1)continue;if(node.left===null)queue.push([newNode(-1),lvl+1]);elsequeue.push([node.left,lvl+1]);if(node.right===null)queue.push([newNode(-1),lvl+1]);elsequeue.push([node.right,lvl+1]);}}//Driver Code Ends// Global pointersletfirst=null,middle=null,last=null,prev=null;// Recursive Function for inorder traversal// to find out the two swapped nodesfunctioncorrectBSTUtil(root){if(root===null)return;// Recur for the left subtreecorrectBSTUtil(root.left);// If this node is smaller than the previous node,// it's violating the BST ruleif(prev!==null&&root.data<prev.data){//first violationif(first===null){first=prev;middle=root;}// second violationelse{last=root;}}// Mark this node as previousprev=root;// Recur for the right subtreecorrectBSTUtil(root.right);}// Function to fix the given BSTfunctioncorrectBST(root){first=middle=last=prev=null;correctBSTUtil(root);if(first!==null&&last!==null)swap(first,last);elseif(first!==null&&middle!==null)swap(first,middle);}// Utility function to swap values of two nodesfunctionswap(a,b){lettemp=a.data;a.data=b.data;b.data=temp;}//Driver Code Starts// Driver code// Constructing the tree with swapped nodes// 6// / \// 10 2// / \ / \// 1 3 7 12letroot=newNode(6);root.left=newNode(10);root.right=newNode(2);root.left.left=newNode(1);root.left.right=newNode(3);root.right.left=newNode(7);root.right.right=newNode(12);correctBST(root);levelOrder(root);//Driver Code Ends