5

I'm having trouble interpreting a certain question about inserting elements to a binary search tree. I'm familiar with preorder, postorder, and inorder traversals, but I'm unfamiliar with the following question:

Suppose that we insert the elements 3, 5, 6, 1, 2, 4, 7 in that order into an initially empty binary search tree.

If I'm only given a set of numbers that are inserted in that order, how am I supposed to make it into a binary search tree? Would 3 be the root? And would I just balance the other numbers to the correct subtree by myself? Wouldn't there be a lot of interpretations in that case? Is there a certain convention that is followed?

Thanks.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
Jigglypuff
  • 1,433
  • 6
  • 24
  • 38

3 Answers3

6

When you add an item to the tree, the existing tree is not reordered. The new item is only added to a leaf node. This means that when you first add 3, 3 will be the root node of the result. When you add 5, it will be on the right of 3, etc. This results in the following tree:

   3
 /   \
1     5
 \   / \
  2 4   6
         \
          7
Sjoerd
  • 74,049
  • 16
  • 131
  • 175
  • Is there a way of telling where to put the 7? Because couldn't it also go to the right of the 4 or 2? – Jigglypuff Jun 26 '11 at 12:34
  • 1
    7 is bigger than 3, so it goes on the right of 3. It is bigger than 5, so it goes to the right of 5, etc. – Sjoerd Jun 26 '11 at 12:37
  • Oh I see. Thank you. I had misunderstood the whole thing all this time thinking you only look at the immediate nodes and not the ones that came before. – Jigglypuff Jun 26 '11 at 12:39
3

Without any further information on rules about how the tree is to be balanced, I would have to assume that it's referring to a "naive" unbalanced tree.

So this:

         3
  /-----/ \-----\
 1               5
  \--\       /--/ \--\
      2     4         6
                       \-\
                          7
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
1

Yes, 3 will be the root, because after the first insertion the whole tree has only one element. Keeping the same logic, if (number, left, right) represents a node you get:

  1. (3,,)

  2. (3,,(5,,))

  3. (3,,(5,,(6,,)))

  4. (3,(1,,),(5,,(6,,)))

  5. (3,(1,,2),(5,,(6,,)))

  6. (3,(1,,2),(5,(4,,),(6,,)))

  7. (3,(1,,2),(5,(4,,),(6,,7)))

Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95