Given an array arr[] which represents a Complete Binary Tree i.e., if index i is the parent, index 2*i + 1 is the left child and index 2*i + 2 is the right child. The task is to find the minimum number of swaps required to convert it into a Binary Search Tree.
Examples:
Input: arr[] = [5, 6, 7, 8, 9, 10, 11] Output: 3 Explanation: Binary tree of the given array:
Swap 1: Swap node 8 with node 5. Swap 2: Swap node 9 with node 10. Swap 3: Swap node 10 with node 7.
So, minimum 3 swaps are required to obtain the below binary search tree:
Input: arr[] = [1, 2, 3] Output: 1 Explanation: Binary tree of the given array:
After swapping node 1 with node 2, obtain the below binary search tree:
Approach:
The idea is to use the fact that inorder traversalof Binary Search Tree is in increasing order of their value. So, find the inorder traversal of the Binary Tree and store it in the array and try to sort the array. Theminimum number of swap required to get the array sorted will be the answer.
C++
// C++ program for Minimum swap required// to convert binary tree to binary search tree#include<bits/stdc++.h>usingnamespacestd;// Function to perform inorder traversal of the binary tree// and store it in vector vvoidinorder(vector<int>&arr,vector<int>&inorderArr,intindex){intn=arr.size();// If index is out of bounds, returnif(index>=n)return;// Recursively visit left subtreeinorder(arr,inorderArr,2*index+1);// Store current node value in vectorinorderArr.push_back(arr[index]);// Recursively visit right subtreeinorder(arr,inorderArr,2*index+2);}// Function to calculate minimum swaps // to sort inorder traversalintminSwaps(vector<int>&arr){intn=arr.size();vector<int>inorderArr;// Get the inorder traversal of the binary treeinorder(arr,inorderArr,0);// Create an array of pairs to store value// and original indexvector<pair<int,int>>t(inorderArr.size());intans=0;// Store the value and its indexfor(inti=0;i<inorderArr.size();i++)t[i]={inorderArr[i],i};// Sort the pair array based on values // to get BST ordersort(t.begin(),t.end());// Find minimum swaps by detecting cyclesfor(inti=0;i<t.size();i++){// If the element is already in the // correct position, continueif(i==t[i].second)continue;// Otherwise, perform swaps until the element// is in the right placeelse{// Swap elements to correct positionsswap(t[i].first,t[t[i].second].first);swap(t[i].second,t[t[i].second].second);}// Check if the element is still not// in the correct positionif(i!=t[i].second)--i;// Increment swap countans++;}returnans;}intmain(){vector<int>arr={5,6,7,8,9,10,11};cout<<minSwaps(arr)<<endl;}
Java
// Java program for Minimum swap required// to convert binary tree to binary search treeimportjava.util.Arrays;classGfG{// Function to perform inorder traversal of the binary tree// and store it in an arraystaticvoidinorder(int[]arr,int[]inorderArr,intindex,int[]counter){intn=arr.length;// Base case: if index is out of bounds, returnif(index>=n)return;// Recursively visit left subtreeinorder(arr,inorderArr,2*index+1,counter);// Store current node value in the inorder arrayinorderArr[counter[0]]=arr[index];counter[0]++;// Recursively visit right subtreeinorder(arr,inorderArr,2*index+2,counter);}// Function to calculate minimum swaps // to sort inorder traversalstaticintminSwaps(int[]arr){intn=arr.length;int[]inorderArr=newint[n];int[]counter=newint[1];// Get the inorder traversal of the binary treeinorder(arr,inorderArr,0,counter);// Create an array of pairs to store the value // and its original indexint[][]t=newint[n][2];intans=0;// Store the value and its original indexfor(inti=0;i<n;i++){t[i][0]=inorderArr[i];t[i][1]=i;}// Sort the array based on values to get BST orderArrays.sort(t,(a,b)->Integer.compare(a[0],b[0]));// Find minimum swaps by detecting cyclesboolean[]visited=newboolean[n];// Iterate through the array to find cyclesfor(inti=0;i<n;i++){// If the element is already visited or in// the correct place, continueif(visited[i]||t[i][1]==i)continue;// Start a cycle and find the number of// nodes in the cycleintcycleSize=0;intj=i;while(!visited[j]){visited[j]=true;j=t[j][1];cycleSize++;}// If there is a cycle, we need (cycleSize - 1)// swaps to sort the cycleif(cycleSize>1){ans+=(cycleSize-1);}}// Return the total number of swapsreturnans;}publicstaticvoidmain(String[]args){int[]arr={5,6,7,8,9,10,11};System.out.println(minSwaps(arr));}}
Python
# Python program for Minimum swap required# to convert binary tree to binary search tree# Function to perform inorder traversal of the binary tree# and store it in an arraydefinorder(arr,inorderArr,index):# If index is out of bounds, returnn=len(arr)ifindex>=n:return# Recursively visit left subtreeinorder(arr,inorderArr,2*index+1)# Store current node value in inorderArrinorderArr.append(arr[index])# Recursively visit right subtreeinorder(arr,inorderArr,2*index+2)# Function to calculate minimum swaps # to sort inorder traversaldefminSwaps(arr):inorderArr=[]# Get the inorder traversal of the binary treeinorder(arr,inorderArr,0)# Create a list of pairs to store value and original indext=[(inorderArr[i],i)foriinrange(len(inorderArr))]ans=0# Sort the list of pairs based on values# to get BST ordert.sort()# Initialize visited arrayvisited=[False]*len(t)# Find minimum swaps by detecting cyclesforiinrange(len(t)):# If already visited or already in the# correct place, skipifvisited[i]ort[i][1]==i:continue# Start a cycle and find the number of # nodes in the cyclecycleSize=0j=i# Process all elements in the cyclewhilenotvisited[j]:visited[j]=Truej=t[j][1]cycleSize+=1# If there is a cycle of size `cycle_size`, we # need `cycle_size - 1` swapsifcycleSize>1:ans+=(cycleSize-1)# Return total number of swapsreturnansif__name__=="__main__":arr=[5,6,7,8,9,10,11]print(minSwaps(arr))
C#
// C# program for Minimum swap required// to convert binary tree to binary search treeusingSystem;usingSystem.Linq;classGfG{// Function to perform inorder traversal of the binary tree// and store it in an arraystaticvoidInorder(int[]arr,int[]inorderArr,intindex,refintcounter){intn=arr.Length;// Base case: if index is out of bounds, returnif(index>=n)return;// Recursively visit left subtreeInorder(arr,inorderArr,2*index+1,refcounter);// Store current node value in inorderArrinorderArr[counter]=arr[index];counter++;// Recursively visit right subtreeInorder(arr,inorderArr,2*index+2,refcounter);}// Function to calculate minimum// swaps to sort inorder traversalstaticintMinSwaps(int[]arr){intn=arr.Length;int[]inorderArr=newint[n];intcounter=0;// Get the inorder traversal of the binary treeInorder(arr,inorderArr,0,refcounter);// Create an array of pairs to store value // and original indexvart=new(int,int)[n];for(inti=0;i<n;i++){t[i]=(inorderArr[i],i);}// Sort the array based on values to get BST orderArray.Sort(t,(a,b)=>a.Item1.CompareTo(b.Item1));// Initialize visited arraybool[]visited=newbool[n];intans=0;// Find minimum swaps by detecting cyclesfor(inti=0;i<n;i++){// If already visited or already in // the correct place, skipif(visited[i]||t[i].Item2==i)continue;// Start a cycle and find the number // of nodes in the cycleintcycleSize=0;intj=i;// Process all elements in the cyclewhile(!visited[j]){visited[j]=true;j=t[j].Item2;cycleSize++;}// If there is a cycle of size `cycle_size`, we// need `cycle_size - 1` swapsif(cycleSize>1){ans+=(cycleSize-1);}}// Return total number of swapsreturnans;}staticvoidMain(string[]args){int[]arr={5,6,7,8,9,10,11};Console.WriteLine(MinSwaps(arr));}}
JavaScript
// Javascript program for Minimum swap required// to convert binary tree to binary search tree// Inorder traversal to get values in sorted orderfunctioninorder(arr,inorderArr,index){// If index is out of bounds, returnif(index>=arr.length)return;// Recursively visit left subtreeinorder(arr,inorderArr,2*index+1);// Store current node value in arrayinorderArr.push(arr[index]);// Recursively visit right subtreeinorder(arr,inorderArr,2*index+2);}// Function to calculate minimum swaps to sort inorder// traversalfunctionminSwaps(arr){letinorderArr=[];// Get the inorder traversal of the binary treeinorder(arr,inorderArr,0);// Create an array of pairs to store value and original// indexlett=inorderArr.map((val,i)=>[val,i]);letans=0;// Sort the pair array based on values to get BST ordert.sort((a,b)=>a[0]-b[0]);// Find minimum swaps by detecting cyclesletvisited=Array(arr.length).fill(false);for(leti=0;i<t.length;i++){// If the element is already in the correct// position, continueif(visited[i]||t[i][1]===i)continue;// Otherwise, perform swaps until the element is in// the right placeletcycleSize=0;letj=i;while(!visited[j]){visited[j]=true;j=t[j][1];cycleSize++;}// If there is a cycle, we need (cycleSize - 1)// swaps to sort the cycleif(cycleSize>1){ans+=(cycleSize-1);}}// Return total number of swapsreturnans;}letarr=[5,6,7,8,9,10,11];console.log(minSwaps(arr));
Output
3
Time Complexity: O(n*logn) where n is the number of elements in array. Auxiliary Space: O(n) because it is using extra space for array
Exercise: Can we extend this to normal binary tree, i.e., a binary tree represented using left and right pointers, and not necessarily complete?
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.