开发者

input value to create binary search trees

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         
            开发者_Go百科        /\  /\
                    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:

  1. Insert the middle of the whole array.
  2. Recursively insert the left and right halves of the array using this procedure.

For example, in your case of the values 1 - 8 with 5 removed, you would sort the value as

1 2 3 5 6 7 8

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 as

 5 2 1 3

Now, you recursively process the other half, 6 7 8, which inserts 7 and then recursively inserts 6 and 8. Overall, this produces the ordering

5 2 1 3 7 6 8

which 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜