On binary search tree,If I give input as “2,1,3,4,5” the tree will be like
2
/\
1 3
\
4
\
5
But with input like “5,2,1,3,7,6,8”.
5
/ \
2 7
/\ /\
1 3 6 8
So my question , how to produce inputs so that above like balanced tree structure is obtained. (I don’t want to use AVL trees) .Do we have tricks to sort or re-arrange numbers in proper way and produce them as input.I’m looking for inputs so that tree can can created height upto 10.
One very simple way to guarantee a balanced tree is to sort the input, then recursively insert the values as follows:
For example, in your case of the values 1 – 8 with 5 removed, you would sort the value as
You would then insert 5, then recursively apply this procedure to the two halves. On the half
1 2 3, you would insert 2, then recursively insert 1 and 3. This gives the ordering so far asNow, you recursively process the other half,
6 7 8, which inserts 7 and then recursively inserts 6 and 8. Overall, this produces the orderingwhich is precisely the ordering you came up with earlier in your post.
This procedure runs in O(n lg n) time. I’m not positive that this is optimal, so if someone else wants to post a better answer I’d love to see it.