Table of contents
1.
Introduction 
1.1.
Problem Statement
1.2.
Sample Examples 
2.
Solution Approach 
2.1.
Steps of Algorithm 
2.2.
Implementation in C++
2.2.1.
Complexity Analysis
3.
Frequently Asked Questions
3.1.
What is the greedy approach? 
3.2.
What is the difference between Breadth-first Search and Depth-first search? 
3.3.
What is the difference between a binary tree and a binary search tree?
3.4.
What is inorder traversal? 
4.
Conclusion 
Last Updated: Mar 27, 2024

Minimum swap required to convert binary tree to binary search tree

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction 

This article will discuss the problem of finding the minimum number of swaps required to convert the given binary tree into the binary search tree. To solve this problem, there is a prerequisite, and you must know how to calculate the minimum number of swaps to sort the array. To study this, you can refer to this blog of coding ninjas.  

Problem Statement

The problem states that we are given a binary tree and can swap any two nodes in the binary tree. We need to calculate the minimum number of swaps required to convert this given binary tree into the binary search tree. 

Sample Examples 

Input: 

Output: 

The minimum number of swaps required is: 3

Explanation:

Swap 1: Swap Node 80 with node 50. 
Swap 2: Swap node 90 with node 100. 
Swap 3: Swap node 100 with node 70. 

 

Input: 

Output: 

The minimum number of swaps required is: 2

 

Explanation:

Swap 1: Swap nodes 1 and 4 
Swap 2: Swap nodes 4 and 3

Solution Approach 

Prerequisite: Minimum number of swaps to sort the array 

The solution is based on the idea that inorder traversal of the binary search tree is always sorted, so we will calculate the inorder traversal of the binary tree and store it in the array. Then we will calculate the minimum number of swaps to sort the array. It will give us the minimum number of swaps to convert the given binary tree into the binary search tree. 

Steps of Algorithm 

  • Take the input of the binary tree in level order traversal form. 
  • Do the inorder traversal of the binary tree, and store inorder traversal into the array.
  • Now calculate the minimum number of swaps required to sort the array. 
  • The result of the minimum number of swaps to sort the array will be our required answer. 
  • Print the answer.  

Implementation in C++

#include <bits/stdc++.h>
using namespace std;
void inorderTraversal(vector<int> arr, vector<int> &inorder, int root)
{
    if (root >= arr.size())
        return;
    // recur for the left subtree
    inorderTraversal(arr, inorder, 2 * root + 1);
    // pushing the root data into the vector
    inorder.push_back(arr[root]);
    // recur for the right subtree
    inorderTraversal(arr, inorder, 2 * root + 2);
}
static bool cmp(vector<int> &x, vector<int> &y)
{
    return x[0] < y[0];
}
int minimumSwap(vector<int> &inorder)
{
    // conatiner to store the element along with the index
    vector<vector<int>> v;
    int n = inorder.size();
    int swaps = 0;
    for (int i = 0; i < n; i++)
    {
        vector<int> temp;
        temp.push_back(inorder[i]);
        temp.push_back(i);
        v.push_back(temp);
    }
    // sorting the array
    sort(v.begin(), v.end(), cmp);
    for (int i = 0; i < n; i++)
    {
        // if indexing matches with the element
        if (i == v[i][1])
            continue;
        else
        {
            // swapping of the elements
            swap(v[i][0], v[v[i][1]][0]);
            swap(v[i][1], v[v[i][1]][1]);
        }
        // is the second element is not equal to i
        if (i != v[i][1])
            --i;
        swaps++;
    }
    return swaps;
}
int main()
{
    vector<int> arr = {50, 60, 70, 80, 90, 100, 110};
    // array to store the inorder traversal of the above tree
    int n = arr.size();
    vector<int> inorder;
    inorderTraversal(arr, inorder, 0);
    // printing the inorder array
    // for (int i = 0; i < n; i++)
    //  cout << inorder[i] << " ";
    // cout << endl;
    cout << "The minimum number of swaps required are : " << minimumSwap(inorder) << endl;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output:

The minimum number of swaps required is: 3 

 

Complexity Analysis

Time Complexity: O(N)

We are only doing linear traversal of the arrays, so time complexity is linear to find the minimum number of swaps to convert binary tree to binary search tree. 

Space Complexity: O(N)

We are creating a temporary array to store the inorder traversal of the given tree, so space complexity is O(N). 

Frequently Asked Questions

What is the greedy approach? 

It is an algorithm to find the problem's optimal solution. In this algorithm, we always choose the next best solution that seems optimal at that step. We build solutions piece by piece to reach the optimal solution.

What is the difference between Breadth-first Search and Depth-first search? 

The BFS uses queue data structure while DFS uses the stack data structure. BFS is more suitable for searching vertices closer to the given source, while DFS is more suitable for solutions away from the source.

What is the difference between a binary tree and a binary search tree?

A tree that has a maximum of 2 children is called a binary tree, whereas a binary search tree is a particular binary tree having the following properties. 

Keys in the left subtree are always smaller than the root's node, whereas keys in the right subtree are greater than the root's node. 

What is inorder traversal? 

In order traversal, we first traverse the left subtree, visit the root, and traverse the right subtree. 

Conclusion 

In this article, we discussed a very interesting problem in which we have to calculate the minimum number of swaps required to convert the given binary tree into the binary search tree Hope you have understood the solution approach. 

 

Recommended problems -

 

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem DesignMachine learning and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc; you must look at the problemsinterview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!!

Live masterclass