2/29/2016 Binary Tree to Binary Search Tree Conversion GeeksforGeeks
http://www.geeksforgeeks.org/binarytreetobinarysearchtreeconversion/ 1/13
CA GATE CS Practice Suggest IDE Q&A
GeeksQuiz
GeeksforGeeks
A computer science portal for geeks
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.
šƒ’Ž• h
)’—–[
he
u N
i n
u N
o k
/—–’—–[
o
u N
k he
u N
i n
šƒ’Ž• i
)’—–[
he
u N
je hl
u N
ie l
/—–’—–[
hl
u N
he ie
u N
l je
Solution
2/29/2016 Binary Tree to Binary Search Tree Conversion GeeksforGeeks
http://www.geeksforgeeks.org/binarytreetobinarysearchtreeconversion/ 2/13
Following is a 3 step solution for converting Binary tree to Binary Search Tree.
1) Create a temp array arr[] that stores inorder traversal of the tree. This step takes O(n) time.
2) Sort the temp array arr[]. Time complexity of this step depends upon the sorting algorithm. In the following
implementation, Quick Sort is used which takes (n^2) time. This can be done in O(nLogn) time using Heap Sort
or Merge Sort.
3) Again do inorder traversal of tree and copy array elements to tree nodes one by one. This step takes O(n)
time.
Following is C implementation of the above approach. The main function to convert is highlighted in the
following code.
u? ! pro‰rƒm to conv•rt "inƒr› 4r•• to "inƒr› 3•ƒrcŠ 4r•• ?u
dinclud•?stdio\Š?
dinclud•?stdli„\Š?
u? ! Š•lp•r function to count nod•s in ƒ "inƒr› 4r•• ?u
int count.od•s struct nod•? root?
?
if root ?? .5,,?
return eZ
return count.od•s root^?l•ft? ?
count.od•s root^?ri‰Št? ? hZ
?
uu &ollowin‰ function is n••d•d for li„rƒr› function qsort?
int compƒr• const void ? ƒY const void ? „?
?
return ?int??ƒ ^ ?int??„ ?Z
?
u? ! Š•lp•r function tŠƒt copi•s cont•nts of ƒrr?? to "inƒr› 4r••\
4Šis functon „ƒsicƒll› do•s )nord•r trƒv•rsƒl of "inƒr› 4r•• ƒnd
on• „› on• cop› ƒrr?? •l•m•nts to "inƒr› 4r•• nod•s ?u
void ƒrrƒ›4o"34 int ?ƒrrY struct nod•? rootY int ?ind•šOptr?
2/29/2016 Binary Tree to Binary Search Tree Conversion GeeksforGeeks
http://www.geeksforgeeks.org/binarytreetobinarysearchtreeconversion/ 3/13
void ƒrrƒ›4o"34 int ?ƒrrY struct nod•? rootY int ?ind•šOptr?
?
uu "ƒs• #ƒs•
if root ?? .5,,?
returnZ
2/29/2016 Binary Tree to Binary Search Tree Conversion GeeksforGeeks
http://www.geeksforgeeks.org/binarytreetobinarysearchtreeconversion/ 4/13
Output:
&ollowin‰ is )nord•r 4rƒv•rsƒl of tŠ• conv•rt•d "34[
l he hl ie je
We will be covering another method for this problem which converts the tree using O(height of tree) extra
space.
Please write comments if you find anything incorrect, or you want to share more information about the topic
discussed above
42 Comments Category: Binary Search Tree
Related Posts:
Count inversions in an array | Set 2 (Using SelfBalancing BST)
Print Common Nodes in Two Binary Search Trees
Construct all possible BSTs for keys 1 to N
K’th smallest element in BST using O(1) Extra Space
Run on IDE
u? now r•cur on ri‰Št cŠild ?u
print)nord•r nod•^?ri‰Št?Z
?
u? riv•r function to t•st ƒ„ov• functions ?u
int mƒin?
?
struct nod• ?root ? .5,,Z
u? #onstructin‰ tr•• ‰iv•n in tŠ• ƒ„ov• fi‰ur•
he
u N
je hl
u N
ie l ?u
root ? n•w.od•he?Z
root^?l•ft ? n•w.od•je?Z
root^?ri‰Št ? n•w.od•hl?Z
root^?l•ft^?l•ft ? n•w.od•ie?Z
root^?ri‰Št^?ri‰Št ? n•w.od•l?Z
uu conv•rt "inƒr› 4r•• to "34
„inƒr›4r••4o"34 root?Z
printfQ&ollowin‰ is )nord•r 4rƒv•rsƒl of tŠ• conv•rt•d "34[ NnQ?Z
print)nord•r root?Z
return eZ
?
2/29/2016 Binary Tree to Binary Search Tree Conversion GeeksforGeeks
http://www.geeksforgeeks.org/binarytreetobinarysearchtreeconversion/ 5/13
Count BST subtrees that lie in given range
Count BST nodes that lie in a given range
Data Structure for a single resource reservations
How to handle duplicates in Binary Search Tree?
(Login to Rate and Mark)
2.8
Average Difficulty : 2.8/5.0
Based on 6 vote(s)
Add to TODO List
Mark as DONE
Writing code in comment? Please use code.geeksforgeeks.org, generate link and share the link here.
42 Comments GeeksforGeeks Login
1
Share
⤤
Sort by Newest
Join the discussion…
•Reply•
HeMan • 6 months ago
One solution that does not use any extra space is :
Perform standard preorder traversal of the given Binary Tree. Instead of printing the value
in preorder, just call insert() function of binary search tree.
BT_2_BST(root)
if(root!=NULL)
1.)*root_BST = insert(root_BST,root>data); //http://geeksquiz.com/binaryse...
2.) preorder(root>left);
3.) preorder(root>right);
△ ▽
•Reply•
holdnet • 2 months ago> HeMan
In your solution original structure of the tree will not be maintained.
△ ▽
HeMan • 2 months ago> holdnet
You are right...Actually.. I'm trying to convert the existing tree to a BST
Recommend
Share ›
Share ›
3 people like this. Sign Up to see what your friends like.LikeShare
2/29/2016 Binary Tree to Binary Search Tree Conversion GeeksforGeeks
http://www.geeksforgeeks.org/binarytreetobinarysearchtreeconversion/ 6/13
•Reply•
You are right...Actually.. I'm trying to convert the existing tree to a BST
without allocating separate space for resulting BST.
△ ▽
•Reply•
Bewkoof_coder • 8 months ago
see more
first call the below function with a=1,where i will gives the size of array,,which i returning
by function,,in second clling its( i ) not of any use.;
then sort array A
then again call the below function with a=0;
int BT_to_BST(struct node *start,int *A,int a){
static int i=1;
static int k=1;
if(start==NULL)
return i;
else{
BT_to_BST(start>left,A,a);
if(a){
1△ ▽
•Reply•
Dipankar Bhardwaj • 8 months ago
http://code.geeksforgeeks.org/...
△ ▽
•Reply•
vergil • 8 months ago
rather than using two separate functions for storeInorder and arrayToBST we can use
either one only and add a boolean flag to coditionally execute either
inorder[*index_ptr] = node>data or node>data = inorder[*index_ptr]
respectively
△ ▽
Yaduvir • 8 months ago
SEE THIS CODE
#include <iostream>
#define MAX 100000000
Share ›
Share ›
Share ›
Share ›
2/29/2016 Binary Tree to Binary Search Tree Conversion GeeksforGeeks
http://www.geeksforgeeks.org/binarytreetobinarysearchtreeconversion/ 7/13
•Reply•
see more
using namespace std;
int size;
struct node
{
int data;
node *left;
node *right;
};
△ ▽
•Reply•
Radhika Bansal` • 9 months ago
According to me the minimum time complexity for this problem is O(n) because at least
once we are to traverse every node.
△ ▽
•Reply•
Monica Shankar • 7 months ago> Radhika Bansal`
the minimum complexity for sorting is O(nlgn) which is greater than O(n)
△ ▽
•Reply•
Guest • a year ago
traverse the given tree in postorder, delete every node & reinsert it into a new BST. This
is O(n+n*log(n)), which is O(n*log(n)).
△ ▽
•Reply•
prashant saxena • a year ago> Guest
This may not create same spatial arrangement of nodes.
1△ ▽
•Reply•
ffff • a year ago
this algo doesn't work in java implementation
△ ▽
•Reply•
prashant saxena • a year ago> ffff
Then your implementation might me wrong. I don't see any issue with the algo.
May be you might want to share your implementation on this forum.
△ ▽
2/29/2016 Binary Tree to Binary Search Tree Conversion GeeksforGeeks
http://www.geeksforgeeks.org/binarytreetobinarysearchtreeconversion/ 8/13
•Reply•
spm • a year ago
see more
My logic is :
1.First do inorder traversal of the given tree and store the keys in an array(Yes this algo
uses auxilliary space :( ).
2.Sort the keys of the tree.<used bubble="" sort="" here="" but="" that="" is="" just=""
to="" verify="" correctness="" of="" algo,should="" be="" using="" quicksort="">
3.Do the inorder traversal of the given tree and replace the node's data values with the
sorted values,this ensures that its a BST as well as the fact that it has the same structure
as given tree.
Please let me know if this is a good way.
/*
Binary Tree to BST Conversion
http://www.geeksforgeeks.org/b...
*/
#include<stdio.h>
#include<stdlib.h>
△ ▽
•Reply•
spm • a year ago> spm
Sorry for writing the code there itself
Refer http://ideone.com/65vj80 for code
△ ▽
indian.samurai • 2 years ago
Create a inorder array which has another column containing the number of child for that
index. In above example it will be:
inorder [0][] = 8 2 4 10 7
inorder [1][] = 0 2 0 4 0
Now sort the first column without changing the values for second, this will become
inorder [0][] = 2 4 7 8 10
inorder [1][] = 0 2 0 4 0
Build a tree using this. index with maximum children count will be root. Next Max on its left
its left child and on right .. right child. Do this recursively.
8
/ \
Share ›
Share ›
2/29/2016 Binary Tree to Binary Search Tree Conversion GeeksforGeeks
http://www.geeksforgeeks.org/binarytreetobinarysearchtreeconversion/ 9/13
•Reply•
/ \
4 10
/ \
2 7
1△ ▽
•Reply•
Rahul • 2 years ago
Following is the constant space and O(n2) solution
http://pastebin.com/FV5hg3H2
△ ▽
•Reply•
Jun • 2 years ago
http://ideone.com/3JSsCy
△ ▽
•Reply•
GS • 2 years ago
Think If we need to do this without extra space :)
I can think of an O(n^2) algo
if some one can think better let us know
△ ▽
•Reply•
GS • 2 years ago> GS
convert to DLL then sort then convert to bst nlogn
4△ ▽
•Reply•
DS+Algo • 2 years ago> GS
We need to retain original structure, man
3△ ▽
•Reply•
Palak Jain • 2 years ago> GS
This soln won't maintain the original structure of binary tree!!
△ ▽
•Reply•
ganesh • 2 years ago
In c we cant create dynamic array using new operator right???
△ ▽
•Reply•
np • 2 years ago> ganesh
correct!!! but if you are using c++ environment to write c code new operator will be
supported
1△ ▽
RACHIT SAXENA • 2 years ago
Share ›
Share ›
Share ›
Share ›
Share ›
Share ›
Share ›
Share ›
Share ›
2/29/2016 Binary Tree to Binary Search Tree Conversion GeeksforGeeks
http://www.geeksforgeeks.org/binarytreetobinarysearchtreeconversion/ 10/13
•Reply•
RACHIT SAXENA • 2 years ago
what about O(log n) space compexity solution
???
△ ▽
•Reply•
Vikas Rajoria • 2 years ago
How is quick sort having n^2 complexity, by all practical needs it yields nlogn . n^2 is
worst case for quick sort, we hardly run into such cases.
3△ ▽
•Reply•
Sudarshan Kj • 2 years ago
what is the use of compare fuction there?
anyone pls tell me
△ ▽
•Reply•
Harry • 2 years ago> Sudarshan Kj
It used by the c function "qsort", refer to http://www.cplusplus.com/refer...
△ ▽
•Reply•
Vivek • 2 years ago
see more
O(n^2) with space O(1)
/? ! program to conv•rt "inary 4r•• to "inary 3•arch 4r•• ?/
#include<stdio.h>
#include<stdlib.h>
vibhor • 2 years ago> Vivek
Why do u say its complexity is O(n^2) it is O(n) only△ ▽
Share ›
Share ›
Share ›
Share ›
Share ›
2/29/2016 Binary Tree to Binary Search Tree Conversion GeeksforGeeks
http://www.geeksforgeeks.org/binarytreetobinarysearchtreeconversion/ 11/13
•Reply•
△ ▽
•Reply•
Deepanshu Arora • 2 years ago> Vivek
It will be really helpful if you would add a documentation to your solution
△ ▽
•Reply•
Guest • 2 years ago> Deepanshu Arora
why do u say that its complexity is n^2 it is O(n) only
△ ▽
•Reply•
Vinodhini • 2 years ago
could you guys post the O(height of tree) solution?
△ ▽
•Reply•
Amit Bgl • 3 years ago
wow code :D
△ ▽
•Reply•
abhishek08aug • 3 years ago
Intelligent :D
△ ▽
•Reply•
prakash_ntk • 3 years ago
see more
//Here is a solution for converting a Binary tree to BST without //using extra space.time complexity=o(n^2)
#onv•rtO"34(nod• root, int curOmax?
?
)f(.5,,??root?
return Z
#onv•rtO"34(root^?right, curOmax?Z
nod• ? maxOnod•?findOn•xt Omax(root,curOmax?Z
int t•mp?root^?dataZ
root^?data?maxOnod•^?dataZ
maxOnod•^?data?t•mpZ
curOmax? maxOnod•^?dataZ
#onv•rtO"34(root^?l•ft, curOmax?Z
?
nod• findOn•xtOmax(nod• root,int pr•Omax?
2△ ▽
Share ›
Share ›
Share ›
Share ›
Share ›
Share ›
Share ›
2/29/2016 Binary Tree to Binary Search Tree Conversion GeeksforGeeks
http://www.geeksforgeeks.org/binarytreetobinarysearchtreeconversion/ 12/13
•Reply•
2△ ▽
•Reply•
algobard • 4 years ago
Can you guys please post the approach which uses O(ht.) space?
△ ▽
•Reply•
Arun • 4 years ago
trav•rs• th• tr•• in pr•^ord•r , mak• th• root nod• corr•ct (m•an root is gr•at•r than l•ft child
do it n(no. of nod•? times. th• tr•• will b• "34 .
4im• compl•xity is nlogn.
△ ▽
•Reply•
Dipanjan • 4 years ago> Arun
9our solution wonPt r•tain th• original "inary tr•• structur•...
△ ▽
•Reply•
Pramod • 4 years ago
see more
import Œava.util.?Z
/**
* 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.
*
* @author ppatil
*
* Example 1
Input:
10
/ \
2 7
/ \
8 4
Output:
8
/ \
4 10
△ ▽
Venki • 4 years ago
I guess we can use modified head sort method. Use an explicit pointer to point next slot in
the inorder traversal, fill it from the top of heap. Algorithmically,
Share ›
Share ›
Share ›
Share ›
Share ›
2/29/2016 Binary Tree to Binary Search Tree Conversion GeeksforGeeks
http://www.geeksforgeeks.org/binarytreetobinarysearchtreeconversion/ 13/13
•Reply•
the inorder traversal, fill it from the top of heap. Algorithmically,
1. Min heapify the binary tree (you need parent pointer).
2. Set inorder successor pointer to left most element.
3. Copy root to successor node.
4. Move the successor node to next node in inorder traversal.
5. Heapify the binary tree (excluding subtrees of inorder successor, little trick needed
here).
6. Repeat 3 to 5 till all nodes are placed.
Binary tree is nothing but random shuffle or data, the any algorithm must atleast take O(N
log N) time.
△ ▽
•Reply•
Keshava • 4 years ago
Would it not be better to make the BST balanced while we are at it?
selecting arr[n/2] as root recursively would do that
△ ▽
Subscribe
✉
Add Disqus to your site Add Disqus Add
d
Privacy=
Share ›
Share ›
@geeksforgeeks, Some rights reserved Contact Us! About Us! Advertise with us!