Open In App

Binary Tree to Binary Search Tree Conversion using STL set

Last Updated : 14 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of the Binary Tree.
This solution will use Sets of C++ STL instead of array-based solution.

Examples: 

Example 1
Input:
          10
         /  \
        2    7
       / \
      8   4
Output:
          8
         /  \
        4    10
       / \
      2   7


Example 2
Input:
          10
         /  \
        30   15
       /      \
      20       5
Output:
          15
         /  \
       10    20
       /      \
      5        30

Solution 

  1. Copy the items of binary tree in a set while doing inorder traversal. This takes O(n log n) time. Note that set in C++ STL is implemented using a Self Balancing Binary Search Tree like Red Black Tree, AVL Tree, etc
  2. There is no need to sort the set as sets in C++ are implemented using Self-balancing binary search trees due to which each operation such as insertion, searching, deletion, etc takes O(log n) time.
  3. Now simply copy the items of set one by one from beginning to the tree while doing inorder traversal of the tree. Care should be taken as when copying each item of set from its beginning, we first copy it to the tree while doing inorder traversal, then remove it from the set as well.

Now the above solution is simpler and easier to implement than the array-based conversion of Binary tree to Binary search tree explained here- Conversion of Binary Tree to Binary Search tree (Set-1), where we had to separately make a function to sort the items of the array after copying the items from tree to it.

Implementation: Program to convert a binary tree to a binary search tree using the set. 

C++




/* CPP program to convert a Binary tree to BST
   using sets as containers. */
#include <bits/stdc++.h>
using namespace std;
 
struct Node {
    int data;
    struct Node *left, *right;
};
 
// function to store the nodes in set while
// doing inorder traversal.
void storeinorderInSet(Node* root, set<int>& s)
{
    if (!root)
        return;
 
    // visit the left subtree first
    storeinorderInSet(root->left, s);
 
    // insertion takes order of O(logn) for sets
    s.insert(root->data);
 
    // visit the right subtree
    storeinorderInSet(root->right, s);
 
} // Time complexity  = O(nlogn)
 
// function to copy items of set one by one
// to the tree while doing inorder traversal
void setToBST(set<int>& s, Node* root)
{
    // base condition
    if (!root)
        return;
 
    // first move to the left subtree and
    // update items
    setToBST(s, root->left);
 
    // iterator initially pointing to the
    // beginning of set
    auto it = s.begin();
 
    // copying the item at beginning of
    // set(sorted) to the tree.
    root->data = *it;
 
    // now erasing the beginning item from set.
    s.erase(it);
 
    // now move to right subtree and update items
    setToBST(s, root->right);
 
} // T(n) = O(nlogn) time
 
// Converts Binary tree to BST.
void binaryTreeToBST(Node* root)
{
    set<int> s;
 
    // populating the set with the tree's
    // inorder traversal data
    storeinorderInSet(root, s);
 
    // now sets are by default sorted as
    // they are implemented using self-
    // balancing BST
 
    // copying items from set to the tree
    // while inorder traversal which makes a BST
    setToBST(s, root);
 
} // Time complexity  =  O(nlogn),
  // Auxiliary Space = O(n) for set.
 
// helper function to create a node
Node* newNode(int data)
{
    // dynamically allocating memory
    Node* temp = new Node();
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
 
// function to do inorder traversal
void inorder(Node* root)
{
    if (!root)
        return;
    inorder(root->left);
    cout << root->data << " ";
    inorder(root->right);
}
 
int main()
{
    Node* root = newNode(5);
    root->left = newNode(7);
    root->right = newNode(9);
    root->right->left = newNode(10);
    root->left->left = newNode(1);
    root->left->right = newNode(6);
    root->right->right = newNode(11);
 
    /* Constructing tree given in the above figure
           5
         /   \
        7     9
       /\    / \
      1  6   10 11   */
 
    // converting the above Binary tree to BST
    binaryTreeToBST(root);
    cout << "Inorder traversal of BST is: " << endl;
    inorder(root);
    return 0;
}


Java




/* Java program to convert a Binary tree to BST
using sets as containers. */
import java.util.*;
 
class Solution
{
static class Node
{
    int data;
    Node left, right;
}
 
// set
static Set<Integer> s = new HashSet<Integer>();
 
// function to store the nodes in set while
// doing inorder traversal.
static void storeinorderInSet(Node root)
{
    if (root == null)
        return;
 
    // visit the left subtree first
    storeinorderInSet(root.left);
 
    // insertion takes order of O(logn) for sets
    s.add(root.data);
 
    // visit the right subtree
    storeinorderInSet(root.right);
 
} // Time complexity = O(nlogn)
 
// function to copy items of set one by one
// to the tree while doing inorder traversal
static void setToBST( Node root)
{
    // base condition
    if (root == null)
        return;
 
    // first move to the left subtree and
    // update items
    setToBST( root.left);
 
    // iterator initially pointing to the
    // beginning of set
    // copying the item at beginning of
    // set(sorted) to the tree.
    root.data = s.iterator().next();
 
    // now erasing the beginning item from set.
    s.remove(root.data);
 
    // now move to right subtree and update items
    setToBST( root.right);
 
} // T(n) = O(nlogn) time
 
// Converts Binary tree to BST.
static void binaryTreeToBST(Node root)
{
    s.clear();
 
    // populating the set with the tree's
    // inorder traversal data
    storeinorderInSet(root);
 
    // now sets are by default sorted as
    // they are implemented using self-
    // balancing BST
 
    // copying items from set to the tree
    // while inorder traversal which makes a BST
    setToBST( root);
 
} // Time complexity = O(nlogn),
// Auxiliary Space = O(n) for set.
 
// helper function to create a node
static Node newNode(int data)
{
    // dynamically allocating memory
    Node temp = new Node();
    temp.data = data;
    temp.left = temp.right = null;
    return temp;
}
 
// function to do inorder traversal
static void inorder(Node root)
{
    if (root == null)
        return;
    inorder(root.left);
    System.out.print(root.data + " ");
    inorder(root.right);
}
 
// Driver code
public static void main(String args[])
{
    Node root = newNode(5);
    root.left = newNode(7);
    root.right = newNode(9);
    root.right.left = newNode(10);
    root.left.left = newNode(1);
    root.left.right = newNode(6);
    root.right.right = newNode(11);
 
    /* Constructing tree given in the above figure
        5
        / \
        7     9
    /\ / \
    1 6 10 11 */
 
    // converting the above Binary tree to BST
    binaryTreeToBST(root);
    System.out.println( "Inorder traversal of BST is: " );
    inorder(root);
}
}
 
// This code is contributed by Arnab Kundu


Python3




# Python3 program to convert a Binary tree
# to BST using sets as containers.
 
# Binary Tree Node
""" A utility function to create a
new BST node """
class newNode:
 
    # Construct to create a newNode
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# function to store the nodes in set
# while doing inorder traversal.
def storeinorderInSet(root, s):
 
    if (not root) :
        return
 
    # visit the left subtree first
    storeinorderInSet(root.left, s)
 
    # insertion takes order of O(logn)
    # for sets
    s.add(root.data)
 
    # visit the right subtree
    storeinorderInSet(root.right, s)
 
# Time complexity = O(nlogn)
 
# function to copy items of set one by one
# to the tree while doing inorder traversal
def setToBST(s, root) :
 
    # base condition
    if (not root):
        return
 
    # first move to the left subtree and
    # update items
    setToBST(s, root.left)
 
    # iterator initially pointing to
    # the beginning of set
    it = next(iter(s))
 
    # copying the item at beginning of
    # set(sorted) to the tree.
    root.data = it
 
    # now erasing the beginning item from set.
    s.remove(it)
 
    # now move to right subtree
    # and update items
    setToBST(s, root.right)
 
# T(n) = O(nlogn) time
 
# Converts Binary tree to BST.
def binaryTreeToBST(root):
 
    s = set()
 
    # populating the set with the tree's
    # inorder traversal data
    storeinorderInSet(root, s)
 
    # now sets are by default sorted as
    # they are implemented using self-
    # balancing BST
 
    # copying items from set to the tree
    # while inorder traversal which makes a BST
    setToBST(s, root)
 
# Time complexity = O(nlogn),
# Auxiliary Space = O(n) for set.
 
# function to do inorder traversal
def inorder(root) :
 
    if (not root) :
        return
    inorder(root.left)
    print(root.data, end = " ")
    inorder(root.right)
 
# Driver Code
if __name__ == '__main__':
 
    root = newNode(5)
    root.left = newNode(7)
    root.right = newNode(9)
    root.right.left = newNode(10)
    root.left.left = newNode(1)
    root.left.right = newNode(6)
    root.right.right = newNode(11)
 
    """ Constructing tree given in
        the above figure
        5
        / \
        7     9
    /\ / \
    1 6 10 11 """
 
    # converting the above Binary tree to BST
    binaryTreeToBST(root)
    print("Inorder traversal of BST is: ")
    inorder(root)
 
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)


C#




// C# program to convert
// a Binary tree to BST
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Solution{
     
class Node
{
  public int data;
  public Node left,
              right;
}
  
// set
static SortedSet<int> s =
       new SortedSet<int>();
  
// function to store the nodes
// in set while doing inorder
// traversal.
static void storeinorderInSet(Node root)
{
  if (root == null)
    return;
 
  // visit the left subtree
  // first
  storeinorderInSet(root.left);
 
  // insertion takes order of
  // O(logn) for sets
  s.Add(root.data);
 
  // visit the right subtree
  storeinorderInSet(root.right);
 
}
   
// Time complexity = O(nlogn)
  
// function to copy items of
// set one by one to the tree
// while doing inorder traversal
static void setToBST(Node root)
{
  // base condition
  if (root == null)
    return;
 
  // first move to the left
  // subtree and update items
  setToBST(root.left);
 
  // iterator initially pointing
  // to the beginning of set copying
  // the item at beginning of set(sorted)
  // to the tree.
  root.data = s.First();
 
  // now erasing the beginning item
  // from set.
  s.Remove(s.First());
 
  // now move to right subtree and
  // update items
  setToBST( root.right);
}
   
// T(n) = O(nlogn) time
 // Converts Binary tree to BST.
static void binaryTreeToBST(Node root)
{
  s.Clear();
 
  // populating the set with
  // the tree's inorder traversal
  // data
  storeinorderInSet(root);
 
  // now sets are by default sorted
  // as they are implemented using
  // self-balancing BST
 
  // copying items from set to the
  // tree while inorder traversal
  // which makes a BST
  setToBST( root);
  
}
   
// Time complexity = O(nlogn),
// Auxiliary Space = O(n) for set.
  
// helper function to create a node
static Node newNode(int data)
{
  // dynamically allocating
  // memory
  Node temp = new Node();
  temp.data = data;
  temp.left = temp.right = null;
  return temp;
}
  
// function to do inorder traversal
static void inorder(Node root)
{
  if (root == null)
    return;
  inorder(root.left);
  Console.Write(root.data + " ");
  inorder(root.right);
}
  
// Driver code
public static void Main(string []args)
{
  Node root = newNode(5);
  root.left = newNode(7);
  root.right = newNode(9);
  root.right.left = newNode(10);
  root.left.left = newNode(1);
  root.left.right = newNode(6);
  root.right.right = newNode(11);
 
  /* Constructing tree given in
  // the above figure
        5
        / \
        7     9
    /\ / \
    1 6 10 11 */
 
  // converting the above Binary
  // tree to BST
  binaryTreeToBST(root);
  Console.Write("Inorder traversal of " +
                "BST is: \n" );
  inorder(root);
}
}
 
// This code is contributed by Rutvik_56


Javascript




<script>
 
// JavaScript program to convert
// a Binary tree to BST
 
class Node
{
  constructor()
  {
    this.data = 0;
    this.right = null;
    this.left = null;
  }
}
  
// set
var s = new Set();
  
// function to store the nodes
// in set while doing inorder
// traversal.
function storeinorderInSet(root)
{
  if (root == null)
    return;
 
  // visit the left subtree
  // first
  storeinorderInSet(root.left);
 
  // insertion takes order of
  // O(logn) for sets
  s.add(root.data);
 
  // visit the right subtree
  storeinorderInSet(root.right);
 
}
   
// Time complexity = O(nlogn)
  
// function to copy items of
// set one by one to the tree
// while doing inorder traversal
function setToBST(root)
{
  // base condition
  if (root == null)
    return;
 
  // first move to the left
  // subtree and update items
  setToBST(root.left);
 
  var tmp = [...s].sort((a,b)=> a-b);
  // iterator initially pointing
  // to the beginning of set copying
  // the item at beginning of set(sorted)
  // to the tree.
  root.data = tmp[0];
 
  // now erasing the beginning item
  // from set.
  s.delete(tmp[0]);
 
  // now move to right subtree and
  // update items
  setToBST( root.right);
}
   
// T(n) = O(nlogn) time
 // Converts Binary tree to BST.
function binaryTreeToBST(root)
{
  s = new Set();
 
  // populating the set with
  // the tree's inorder traversal
  // data
  storeinorderInSet(root);
 
  // now sets are by default sorted
  // as they are implemented using
  // self-balancing BST
 
  // copying items from set to the
  // tree while inorder traversal
  // which makes a BST
  setToBST( root);
  
}
   
// Time complexity = O(nlogn),
// Auxiliary Space = O(n) for set.
  
// helper function to create a node
function newNode(data)
{
  // dynamically allocating
  // memory
  var temp = new Node();
  temp.data = data;
  temp.left = temp.right = null;
  return temp;
}
  
// function to do inorder traversal
function inorder(root)
{
  if (root == null)
    return;
  inorder(root.left);
  document.write(root.data + " ");
  inorder(root.right);
}
  
// Driver code
var root = newNode(5);
root.left = newNode(7);
root.right = newNode(9);
root.right.left = newNode(10);
root.left.left = newNode(1);
root.left.right = newNode(6);
root.right.right = newNode(11);
/* Constructing tree given in
// the above figure
      5
      / \
      7     9
  /\ / \
  1 6 10 11 */
// converting the above Binary
// tree to BST
binaryTreeToBST(root);
document.write("Inorder traversal of " +
              "BST is: <br>" );
inorder(root);
 
</script>


Output

Inorder traversal of BST is: 
1 5 6 7 9 10 11 

Complexity Analysis:

  • Time Complexity: O(n Log n) 
  • Auxiliary Space: (n)


Similar Reads

Binary Tree to Binary Search Tree Conversion
Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of Binary Tree. Examples Example 1Input: 10 / \ 2 7 / \ 8 4Output: 8 / \ 4 10 / \ 2 7Example 2Input: 10 / \ 30 15 / \ 20 5Output: 15 / \ 10 20 / \ 5 30Solution: Following is a 3 step solution for converting Binary tre
15+ min read
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
Conversion of whole String to uppercase or lowercase using STL in C++
Given a string, convert the whole string to uppercase or lowercase using STL in C++. Examples: For uppercase conversionInput: s = "String"Output: s = "STRING" For lowercase conversionInput: s = "String"Output: s = "string" Functions used : transform : Performs a transformation on given array/string. toupper(char c): Returns the upper case version o
1 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
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 swap required to convert binary tree to binary search tree
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: Swap
8 min read
Difference between Binary Tree and Binary Search Tree
Binary Tree Data Structure:A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right children.  Binary Search Tree Data Structure (BST):A binary search tree is a hierarchical data structure where each node has at most two children, w
2 min read
Find the Deepest Node in a Binary Tree Using Queue STL - SET 2
Given a binary tree. The task is to find the value of the deep­est node in the given binary tree. Examples: Input: Root of below tree 1 / \ 2 3 / \ / \ 4 5 6 7 \ 8 Output: 8 Input: Root of below tree 1 / \ 2 3 / 6 Output: 6 Approach: We have already discussed the two different ways to find the deepest node in a binary tree in this post. Here, we wi
6 min read
Gray to Binary and Binary to Gray conversion
Binary Number is the default way to store numbers, but in many applications, binary numbers are difficult to use and a variety of binary numbers is needed. This is where Gray codes are very useful. Gray code has a property that two successive numbers differ in only one bit because of this property gray code does the cycling through various states w
13 min read
three90RightbarBannerImg