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
- 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
- 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.
- 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++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *left, *right;
};
void storeinorderInSet(Node* root, set< int >& s)
{
if (!root)
return ;
storeinorderInSet(root->left, s);
s.insert(root->data);
storeinorderInSet(root->right, s);
}
void setToBST(set< int >& s, Node* root)
{
if (!root)
return ;
setToBST(s, root->left);
auto it = s.begin();
root->data = *it;
s.erase(it);
setToBST(s, root->right);
}
void binaryTreeToBST(Node* root)
{
set< int > s;
storeinorderInSet(root, s);
setToBST(s, root);
}
Node* newNode( int data)
{
Node* temp = new Node();
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
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);
binaryTreeToBST(root);
cout << "Inorder traversal of BST is: " << endl;
inorder(root);
return 0;
}
|
Java
import java.util.*;
class Solution
{
static class Node
{
int data;
Node left, right;
}
static Set<Integer> s = new HashSet<Integer>();
static void storeinorderInSet(Node root)
{
if (root == null )
return ;
storeinorderInSet(root.left);
s.add(root.data);
storeinorderInSet(root.right);
}
static void setToBST( Node root)
{
if (root == null )
return ;
setToBST( root.left);
root.data = s.iterator().next();
s.remove(root.data);
setToBST( root.right);
}
static void binaryTreeToBST(Node root)
{
s.clear();
storeinorderInSet(root);
setToBST( root);
}
static Node newNode( int data)
{
Node temp = new Node();
temp.data = data;
temp.left = temp.right = null ;
return temp;
}
static void inorder(Node root)
{
if (root == null )
return ;
inorder(root.left);
System.out.print(root.data + " " );
inorder(root.right);
}
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 );
binaryTreeToBST(root);
System.out.println( "Inorder traversal of BST is: " );
inorder(root);
}
}
|
Python3
class newNode:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def storeinorderInSet(root, s):
if ( not root) :
return
storeinorderInSet(root.left, s)
s.add(root.data)
storeinorderInSet(root.right, s)
def setToBST(s, root) :
if ( not root):
return
setToBST(s, root.left)
it = next ( iter (s))
root.data = it
s.remove(it)
setToBST(s, root.right)
def binaryTreeToBST(root):
s = set ()
storeinorderInSet(root, s)
setToBST(s, root)
def inorder(root) :
if ( not root) :
return
inorder(root.left)
print (root.data, end = " " )
inorder(root.right)
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 )
binaryTreeToBST(root)
print ( "Inorder traversal of BST is: " )
inorder(root)
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Solution{
class Node
{
public int data;
public Node left,
right;
}
static SortedSet< int > s =
new SortedSet< int >();
static void storeinorderInSet(Node root)
{
if (root == null )
return ;
storeinorderInSet(root.left);
s.Add(root.data);
storeinorderInSet(root.right);
}
static void setToBST(Node root)
{
if (root == null )
return ;
setToBST(root.left);
root.data = s.First();
s.Remove(s.First());
setToBST( root.right);
}
static void binaryTreeToBST(Node root)
{
s.Clear();
storeinorderInSet(root);
setToBST( root);
}
static Node newNode( int data)
{
Node temp = new Node();
temp.data = data;
temp.left = temp.right = null ;
return temp;
}
static void inorder(Node root)
{
if (root == null )
return ;
inorder(root.left);
Console.Write(root.data + " " );
inorder(root.right);
}
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);
binaryTreeToBST(root);
Console.Write( "Inorder traversal of " +
"BST is: \n" );
inorder(root);
}
}
|
Javascript
<script>
class Node
{
constructor()
{
this .data = 0;
this .right = null ;
this .left = null ;
}
}
var s = new Set();
function storeinorderInSet(root)
{
if (root == null )
return ;
storeinorderInSet(root.left);
s.add(root.data);
storeinorderInSet(root.right);
}
function setToBST(root)
{
if (root == null )
return ;
setToBST(root.left);
var tmp = [...s].sort((a,b)=> a-b);
root.data = tmp[0];
s. delete (tmp[0]);
setToBST( root.right);
}
function binaryTreeToBST(root)
{
s = new Set();
storeinorderInSet(root);
setToBST( root);
}
function newNode(data)
{
var temp = new Node();
temp.data = data;
temp.left = temp.right = null ;
return temp;
}
function inorder(root)
{
if (root == null )
return ;
inorder(root.left);
document.write(root.data + " " );
inorder(root.right);
}
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);
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)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
14 Sep, 2022
Like Article
Save Article