Binary Tree to Binary Search Tree Conversion using STL set

Difficulty Level Medium
Frequently asked in Amazon Coursera Google Indeed Microsoft OYO Rooms
Binary Search Tree Binary Tree TreeViews 1638

Problem Statement

We are given a binary tree and we need to convert it into a binary search tree. The problem “Binary Tree to Binary Search Tree Conversion using STL set” asks to do conversion using STL set. We have already discussed converting the binary tree into BST but we had not discussed conversion using Set. While conversion one thing which needs to be checked is that the original tree structure must remain the same.

Example

Input

Output

Binary Tree to Binary Search Tree Conversion using STL set

 

Approach to convert binary tree into BST using Set

We have already discussed the conversion of binary tree to binary search tree, but here we will be using an inbuilt STL Set. So one of the ways could be to first construct a balanced binary search tree that is an AVL tree or Red-Black tree. And then we do an inorder traversal of the newly created tree and copy the contents back to the original tree in a similar inorder fashion.

The approach discussed above requires the creation of an unnecessary self-balancing binary tree. So to avoid this we discussed an array-based approach. In that approach, we first did a traversal of the three and then sorted the array. Again with an inorder traversal, we replaced the elements in the initial tree.

In this approach, we will not create an array and then sort it. We will use a set that keeps the element in a sorted fashion. Thus we will traverse the tree and keep on inserting the element into the set. Afterward, we will replace the elements in the given tree.

Code

C++ code to convert binary tree into BST using Set

#include <bits/stdc++.h>
using namespace std;

// defines the structure of a tree node
struct node{
    int data;
    node* left;
    node* right;
};

// inserts the given tree elements into the set
void insertIntoSet(node* root, set<int> &treeSet){
    if(root){
        insertIntoSet(root->left, treeSet);
        treeSet.insert(root->data);
        insertIntoSet(root->right, treeSet);
    }
}

// replace the elements of the initial tree
// with elements in treeSet in in-order fashion
void modifyBinaryTreeIntoBST(node* root, set<int> &treeSet)
{
    if(root){
        modifyBinaryTreeIntoBST(root->left, treeSet);
        root->data = *(treeSet.begin());
        treeSet.erase(treeSet.begin());
        modifyBinaryTreeIntoBST(root->right, treeSet);
    }
}

// Converts Binary tree to BST
void binaryTreeToBST(node* root)
{
    set<int> treeSet;
    // first fill the set
    insertIntoSet(root, treeSet);
    // then replace the elements in initial tree
    modifyBinaryTreeIntoBST(root, treeSet);
}

// creates and returns a new node with supplied node value
node* create(int data){
    node *tmp = new node();
    tmp->data = data;
    tmp->left = tmp->right = NULL;
    return tmp;
}

// simple in-order traversal
void inorder(node *root){
    if(root){
        inorder(root->left);
        cout<<root->data;
        inorder(root->right);
    }
}

int main()
{
    // constructing a binary tree
    // same as shown above
    node *root = create(1);
    root->right = create(2);
    root->right->left = create(4);
    root->right->left->left = create(5);
    root->right->left->right = create(3);

    cout<<"Inorder Traversal of given binary tree"<<endl;
    inorder(root);cout<<endl;
    binaryTreeToBST(root);
    cout<<"Inorder Traversal of modified tree\n";
    inorder(root);
}
Inorder Traversal of given binary tree
15432
Inorder Traversal of modified tree
12345

Java code to convert binary tree into BST using Set

import java.util.*;
import java.lang.*;
import java.io.*;
 
class node{
  int data;
  node left;
  node right;
}
 
class Tree{
  // creates and returns a new node with supplied node value
  static node create(int data){
    node tmp = new node();
    tmp.data = data;
    tmp.left = null;
    tmp.right = null;
    return tmp;
  }

  // inserts the given tree elements into the set
  static void insertIntoSet(node root, TreeSet<Integer> treeSet){
    if(root != null){
      insertIntoSet(root.left, treeSet);
      treeSet.add(root.data);
      insertIntoSet(root.right, treeSet);
    }
  }

  // replace the elements of the initial tree
  // with elements in treeSet in in-order fashion
  static void modifyBinaryTreeIntoBST(node root, TreeSet<Integer> treeSet)
  {
    if(root != null){
      modifyBinaryTreeIntoBST(root.left, treeSet);
      root.data = treeSet.pollFirst();
      modifyBinaryTreeIntoBST(root.right, treeSet);
    }
  }

  // Converts Binary tree to BST
  static void binaryTreeToBST(node root)
  {
    TreeSet<Integer> treeSet = new TreeSet<>();
    // first fill the set
    insertIntoSet(root, treeSet);
    // then replace the elements in initial tree
    modifyBinaryTreeIntoBST(root, treeSet);
  }

  // simple in-order traversal
  static void inorder(node root){
    if(root != null){
      inorder(root.left);
      System.out.print(root.data);
      inorder(root.right);
    }
  }

  public static void main(String[] args)
  {
    // constructing a binary tree
    // same as shown above
    node root = create(1);
    root.right = create(2);
    root.right.left = create(4);
    root.right.left.left = create(5);
    root.right.left.right = create(3);

    System.out.println("Inorder Traversal of given binary tree");
    inorder(root);
    System.out.println();
    binaryTreeToBST(root);
    System.out.println("Inorder Traversal of modified tree");
    inorder(root);
  }
}
Inorder Traversal of given binary tree
15432
Inorder Traversal of modified tree
12345

Complexity Analysis

Time Complexity

O(N log N),  where N is the number of elements in the tree. Here the logarithmic factor came because of the set. Set data structure requires log N time to insert, search, and delete an element.

Space Complexity

O(N), here we have used extra space to store the nodes in the set. Thus the algorithm for conversion itself has linear space complexity and the program as a whole also has linear space complexity.

Translate »