0

When I am trying to print level Order of BST, this question prompted me.

Here is a

Pre-Order Sequence: 4, 1, 2, 3, 5, 6, 7, 8
In_order Sequence : 1, 2, 3, 4, 5, 6, 7, 8

A level order sequence for a BST with above pre_order and In_order is [4, 2, 6, 1, 3, 5, 7, 8]

However, for the same Pre-order an In-order sequence this level order sequence seems possible. [4, 1, 5, 2, 6, 3, 7, 8]. I don't know how. I am trying to figure this out.

I am unable to construct BST in paper (drawing) that satisfies all the pre_order, In-order and level order sequences.

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
brain storm
  • 30,124
  • 69
  • 225
  • 393

2 Answers2

2

If you have in-order traversal together with one of pre/post-order, that is enough to reconstruct a binary tree. Moreover, in case of BST (binary search tree), post-order or pre-order alone is sufficient.

In your case, reconstructing a BST from pre-order 4, 1, 2, 3, 5, 6, 7, 8 gives the following BST:

     4
   /   \
  1     5
   \     \
    2     6
     \     \
      3     7
             \
              8

which gives, again unique, level-order traversal [4,1,5,2,6,3,7,8].

See also:

Miljen Mikic
  • 14,765
  • 8
  • 58
  • 66
  • my doubt is for the above given preOrder and Inorder, why two level order sequences are possible? – brain storm Jun 24 '15 at 06:47
  • your first level order is wrong.means if you construct tree from given preorder & in order you will get unique tree & level order for that tree will be [4, 1, 5, 2, 6, 3, 7, 8] not [4, 2, 6, 1, 3, 5, 7, 8] – nikhil jain Jun 24 '15 at 06:55
1

Following combination will generate unique binary tree(which can be BST).

Inorder and Preorder.
Inorder and Postorder.
Inorder and Level-order.

So in your case inorder & pre order are given which will generate unique binary tree which is BST in your case so level order will be unique for that tree.

Pre-Order Sequence: 4, 1, 2, 3, 5, 6, 7, 8
In_order Sequence : 1, 2, 3, 4, 5, 6, 7, 8

SO tree will be

level 0- 4
level 1- 1,5
level 2- 2,6
level 3- 3,7
level 4- 8

Level order is

4,1,5,2,6,3,7,8

in sort there will always unique level order traversal

nikhil jain
  • 105
  • 9
  • look at this. I have some related question. http://stackoverflow.com/questions/31020267/converting-sorted-linked-list-to-balanced-binarytree-not-returning-correctly – brain storm Jun 24 '15 at 07:24