Open In App

Minimum swap required to convert binary tree to binary search tree

Last Updated : 22 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given the array representation of 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 swap required to convert it into Binary Search Tree.

Examples:  

Input : arr[] = { 5, 6, 7, 8, 9, 10, 11 }
Output : 3
Binary tree of the given array:

dig11

Swap 1: Swap node 8 with node 5.
Swap 2: Swap node 9 with node 10.
Swap 3: Swap node 10 with node 7.

dig21

So, minimum 3 swaps are required.
Input : arr[] = { 1, 2, 3 }
Output : 1
Binary tree of the given array:

dig3

After swapping node 1 with node 2.

dig41

So, only 1 swap required.

Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.

Approach :

The idea is to use the fact that inorder traversal of 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. The minimum number of swap required to get the array sorted will be the answer.

Below is the implementation of the above approach:

C++




// C++ program for Minimum swap required
// to convert binary tree to binary search tree
#include<bits/stdc++.h>
using namespace std;
 
// Inorder Traversal of Binary Tree
void inorder(int a[], std::vector<int> &v,
                        int n, int index)
{
    // if index is greater or equal to vector size
    if(index >= n)
        return;
    inorder(a, v, n, 2 * index + 1);
     
    // push elements in vector
    v.push_back(a[index]);
    inorder(a, v, n, 2 * index + 2);
}
 
// Function to find minimum swaps to sort an array
int minSwaps(std::vector<int> &v)
{
    std::vector<pair<int,int> > t(v.size());
    int ans = 0;
    for(int i = 0; i < v.size(); i++)
        t[i].first = v[i], t[i].second = i;
     
    sort(t.begin(), t.end());
    for(int i = 0; i < t.size(); i++)
    {
        // second element is equal to i
        if(i == t[i].second)
            continue;
        else
        {
            // swapping of elements
            swap(t[i].first, t[t[i].second].first);
            swap(t[i].second, t[t[i].second].second);
        }
         
        // Second is not equal to i
        if(i != t[i].second)
            --i;
        ans++;
    }
    return ans;
}
 
// Driver code
int main()
{
    int a[] = { 5, 6, 7, 8, 9, 10, 11 };
    int n = sizeof(a) / sizeof(a[0]);
    std::vector<int> v;
    inorder(a, v, n, 0);
    cout << minSwaps(v) << endl;
}
 
// This code is contributed by code_freak


Java




// Java program for Minimum swap required
// to convert binary tree to binary search tree
import java.util.*;
 
public class GFG{
 
    // Pair class
    static class Pair{
        int first, second;
 
        Pair(int a, int b){
            first = a;
            second = b;
        }
    }
     
    // Inorder Traversal of Binary Tree
    static void inorder(int a[], Vector<Integer> v, int n, int index)
    {
        // if index is greater or equal to vector size
        if(index >= n)
            return;
             
        inorder(a, v, n, 2 * index + 1);
         
        // push elements in vector
        v.add(a[index]);
         
        inorder(a, v, n, 2 * index + 2);
    }
     
    // Function returns the
    // minimum number of swaps
    // required to sort the array
    // Refer :
    public static int minSwaps(Vector<Integer> arr)
    {
        int n = arr.size();
  
        ArrayList < Pair > arrpos = new ArrayList < Pair > ();
        for (int i = 0; i < n; i++)
             arrpos.add(new Pair(arr.get(i), i));
  
        // Sort the array by array element values to
        // get right position of every element as the
        // elements of second array.
        arrpos.sort(new Comparator<Pair>()
        {
            @Override
            public int compare(Pair o1, Pair o2)
            {
                return o1.first - o2.first;
            }
        });
  
        // To keep track of visited elements. Initialize
        // all elements as not visited or false.
        Boolean[] vis = new Boolean[n];
        Arrays.fill(vis, false);
  
        // Initialize result
        int ans = 0;
  
        // Traverse array elements
        for (int i = 0; i < n; i++)
        {
            // already swapped and corrected or
            // already present at correct pos
            if (vis[i] || arrpos.get(i).second == i)
                continue;
  
            // find out the number of  node in
            // this cycle and add in ans
            int cycle_size = 0;
            int j = i;
            while (!vis[j])
            {
                vis[j] = true;
  
                // move to next node
                j = arrpos.get(j).second;
                cycle_size++;
            }
  
            // Update answer by adding current cycle.
            if(cycle_size > 0)
            {
                ans += (cycle_size - 1);
            }
        }
  
        // Return result
        return ans;
    }
 
    // Driver code
    public static void main(String args[])
    {
        int a[] = { 5, 6, 7, 8, 9, 10, 11 };
        int n = a.length;
         
        Vector<Integer> v = new Vector<Integer>();
 
        inorder(a, v, n, 0);
 
        System.out.println(minSwaps(v));
    }
}


Python3




# Python3 program for Minimum swap required
# to convert binary tree to binary search tree
 
# Inorder Traversal of Binary Tree
def inorder(a, n, index):
     
    global v
     
    # If index is greater or equal to
    # vector size
    if (index >= n):
        return
     
    inorder(a, n, 2 * index + 1)
 
    # Push elements in vector
    v.append(a[index])
    inorder(a, n, 2 * index + 2)
 
# Function to find minimum swaps
# to sort an array
def minSwaps():
     
    global v
    t = [[0, 0] for i in range(len(v))]
    ans = -2
 
    for i in range(len(v)):
        t[i][0], t[i][1] = v[i], i
 
    t, i = sorted(t), 0
 
    while i < len(t):
         
        # break
        # second element is equal to i
        if (i == t[i][1]):
            i += 1
            continue
        else:
             
            # Swapping of elements
            t[i][0], t[t[i][1]][0] = t[t[i][1]][0], t[i][0]
            t[i][1], t[t[i][1]][1] = t[t[i][1]][1], t[i][1]
 
        # Second is not equal to i
        if (i == t[i][1]):
            i -= 1
 
        i += 1
 
        ans += 1
 
    return ans
 
# Driver Code
if __name__ == '__main__':
     
    v = []
    a = [ 5, 6, 7, 8, 9, 10, 11 ]
    n = len(a)
    inorder(a, n, 0)
 
    print(minSwaps())
 
# This code is contributed by mohit kumar 29


C#




// C# program for Minimum swap required
// to convert binary tree to binary search tree
using System;
using System.Collections.Generic;
using System.Linq;
 
class GFG {
 
    // Pair class
    public class Pair {
        public int first, second;
 
        public Pair(int a, int b)
        {
            first = a;
            second = b;
        }
    }
 
    // Inorder Traversal of Binary Tree
    public static void inorder(int[] a, List<int> v, int n,
                               int index)
    {
        // if index is greater or equal to vector size
        if (index >= n)
            return;
 
        inorder(a, v, n, 2 * index + 1);
 
        // push elements in vector
        v.Add(a[index]);
 
        inorder(a, v, n, 2 * index + 2);
    }
 
    // Function returns the
    // minimum number of swaps
    // required to sort the array
    // Refer :
 
    public static int minSwaps(List<int> arr)
    {
 
        int n = arr.Count();
 
        List<Pair> arrpos = new List<Pair>();
 
        for (int i = 0; i < n; i++)
            arrpos.Add(new Pair(arr[i], i));
 
        // Sort the array by array element values to
        // get right position of every element as the
        // elements of second array.
        arrpos.Sort((x, y) => x.first - y.first);
 
        // To keep track of visited elements. Initialize
        // all elements as not visited or false.
        bool[] vis = new bool[n];
 
        for (int i = 0; i < n; i++)
            vis[i] = false;
 
        // Initialize result
        int ans = 0;
 
        // Traverse array elements
        for (int i = 0; i < n; i++) {
            // already swapped and corrected or
            // already present at correct pos
            if (vis[i] || arrpos[i].first == i)
                continue;
 
            // find out the number of  node in
            // this cycle and add in ans
            int cycle_size = 0;
            int j = i;
            while (!vis[j]) {
                vis[j] = true;
 
                // move to next node
                j = arrpos[j].second;
                cycle_size++;
            }
            // Update answer by adding current cycle.
            if (cycle_size > 0)
                ans += (cycle_size - 1);
        }
        // Return result
        return ans;
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        int[] a = { 5, 6, 7, 8, 9, 10, 11 };
        int n = a.Length;
 
        List<int> v = new List<int>();
 
        inorder(a, v, n, 0);
 
        Console.WriteLine(minSwaps(v));
    }
}
 
// This Code is contributed by Tapesh(tapeshdua420)


Javascript




<script>
// Javascript program for Minimum swap required
// to convert binary tree to binary search tree
 
// Inorder Traversal of Binary Tree
function inorder(a, n, index)
{
    // If index is greater or equal to
    // vector size
    if (index >= n)
        return
      
    inorder(a, n, 2 * index + 1)
  
    // Push elements in vector
    v.push(a[index])
    inorder(a, n, 2 * index + 2)
}
 
// Function to find minimum swaps to sort an array
function minSwaps()
{
    let t=new Array(v.length);
    let ans = -2
     
    for(let i=0;i<v.length;i++)
    {
        t[i]=new Array(2);
        for(let j=0;j<2;j++)
        {
            t[i][j]=0;
        }
    }
     
    for(let i=0;i<v.length;i++)
    {
        t[i][0]=v[i];
        t[i][1]=i;
    }
     
    t.sort(function(a,b){return a[0] - b[0];});
    let i=0;
     
    while(i<t.length)
    {
         
        // break
        // second element is equal to i
        if (i == t[i][1])
        {    i += 1;
            continue;
        }
        else{
              
            // Swapping of elements
            t[i][0], t[t[i][1]][0] = t[t[i][1]][0], t[i][0];
            t[i][1], t[t[i][1]][1] = t[t[i][1]][1], t[i][1];
         }
        // Second is not equal to i
        if (i == t[i][1])
            i -= 1;
  
        i += 1;
  
        ans += 1;
    }
     
     
     return ans;
      
}
// Driver code
let v=[];
let a=[ 5, 6, 7, 8, 9, 10, 11];
let n=a.length;
inorder(a, n, 0);
document.write(minSwaps());
     
 
// This code is contributed by patel2127
</script>


Output

3

Time Complexity: O(n*logn)
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?



Previous Article
Next Article

Similar Reads

Binary Search Tree vs Ternary Search Tree
For effective searching, insertion, and deletion of items, two types of search trees are used: the binary search tree (BST) and the ternary search tree (TST). Although the two trees share a similar structure, they differ in some significant ways. FeatureBinary Search Tree (BST)Ternary Search Tree (TST)NodeHere, each node has at most two children. H
3 min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Convert a Binary Search Tree into a Skewed tree in increasing or decreasing order
Given a Binary Search Tree and a binary integer K, the task is to convert Binary search tree into a Skewed Tree in increasing order if K = 0 or in decreasing order if K = 1. Examples: Input: K = 0, 5 / \ 3 6 Output: 3 \ 5 \ 6 Input: K = 1, 2 / \ 1 3 Output: 3 \ 2 \ 1 Approach: The key observation in the problem is that the first node of the skewed
10 min read
Flatten a Binary Search Tree to convert the tree into a wave list in place only
Given a Binary Search Tree consisting of N distinct nodes, the task is to flatten the given Binary Search Tree to convert the tree into a wave list. A wave list arr[0..n-1] is called a wave list if arr[0] &gt;= arr[1] &lt;= arr[2] &gt;= arr[3] &lt;= arr[4] &gt;= ... . Examples: Input: 1 / \ 0 10Output: 0 \ 10 \ 1 Input: 3 / \ 1 7 / \ / \ 0 2 5 10 O
12 min read
Minimum cost to convert one given string to another using swap, insert or delete operations
Given two strings A and B of length N and M respectively, the task is to find the minimum cost to convert string A to B using the following operations: A character of string A can be swapped from another character of the same string. Cost = 0.A character can be deleted from string B or can be inserted in the string A. Cost = 1. Examples: Input: A =
6 min read
Convert a Binary Tree into its Mirror Tree (Invert Binary Tree)
Given a binary tree, the task is to convert the binary tree into its Mirror tree. Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged. Recommended PracticeMirror TreeTry It!The idea is to traverse recursively and swap the right and left subtrees after traversing the subtrees. Follow
15+ min read
Find the minimum Sub-tree with target sum in a Binary search tree
Given a binary tree and a target, find the number of nodes in the minimum sub-tree with the given sum equal to the target which is also a binary search tree. Examples: Input: 13 / \ 5 23 / \ / \ N 17 N N / 16Target: 38Output: 3Explanation: 5, 17, 16 is the smallest subtree with length 3. Input: 7 / \ N 23 / \ 10 23 / \ / \ N 17 N NTarget: 73Output:
9 min read
Search N elements in an unbalanced Binary Search Tree in O(N * logM) time
Given an Unbalanced binary search tree (BST) of M nodes. The task is to find the N elements in the Unbalanced Binary Search Tree in O(N*logM) time. Examples: Input: search[] = {6, 2, 7, 5, 4, 1, 3}. Consider the below tree Output:FoundNot FoundFoundFoundFoundFoundNot Found Naive Approach: For each element, we will try to search for that element in
8 min read
Meta Binary Search | One-Sided Binary Search
Meta binary search (also called one-sided binary search by Steven Skiena in The Algorithm Design Manual on page 134) is a modified form of binary search that incrementally constructs the index of the target value in the array. Like normal binary search, meta binary search takes O(log n) time. Meta Binary Search, also known as One-Sided Binary Searc
9 min read
Minimum swaps required to convert one binary string to another
Given two binary string M and N of equal length, the task is to find a minimum number of operations (swaps) required to convert string N to M. Examples: Input: str1 = "1101", str2 = "1110" Output: 1 Swap last and second last element in the binary string, so that it become 1101 Input: str1 = "1110000", str2 = "0001101" Output: 3 Approach: Initialize
5 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg