1

I have this output, I just need to understood, how they used those indexes to represent a binary tree?

How many numbers?: 6

Enter 1st number: 50
Enter 2nd number: 60
Enter 3rd number: 40
Enter 4th number: 15
Enter 5th number: 30
Enter 6th number: 27

BST Array:
[0]     50
[1]     40
[2]     60
[3]     15
[8]     30
[17]    27

It starts from 0,1,2,3 then suddenly turn to index 8 then 17 (All other indexes are empty I guess, but why index 8 then 17?).

4
  • 2
    Is there a question there somewhere? You need to provide some extra context. Commented Apr 16, 2012 at 13:29
  • it's a representation of a binary tree through an array. Commented Apr 16, 2012 at 13:30
  • I don't think it's clear what 1st number, 2nd number, etc means. I assume these are numbers you are adding to the binary tree but the ordering or the intended space on the tree are not clear. Storing a binary tree in an array is a very common idea and should come up quickly after a little searching. If you have a particular question about it, maybe you can rephrase? Commented Apr 16, 2012 at 13:38
  • 1
    Most of the answer depends on the exact type of binary tree, the mapping is probably bitwise but that's only a guess. Commented Apr 16, 2012 at 13:41

1 Answer 1

2

This seems to be a plain binary tree without balancing. I guess it's something like this:

root -> index 0

left of root/index 0 -> index 1

right of root/index 0 -> index 2

left of index 1 -> index 3

right of index 1 -> index 4

left of index 2 -> index 5

right of index 2 -> index 6

left of index 3 -> index 7

right of index 3 -> index 8

left of index 4 -> index 9

right of index 4 -> index 10

...

left of index i -> 2*i + 1

right of index i -> 2*i + 2

On the example:

       50
      /  \
    40    60
  /
15
  \ 
  30
  /
 27

For example, 15 is located at index 3. 30 is its right child and hence will be at index 2*3 + 2 = 8. 27 is the left child of the element at index 8 and hence located at index 2 * 8 + 1 = 17.

Sign up to request clarification or add additional context in comments.

2 Comments

btw: what kind of traversal is this?
It's no traversal. It's just the simple insertion algorithm: search for the element you want to insert and if there nothing to continue, insert it there. You start at the root and for every node you go left if the element in question is smaller than the element at that node and right if it is larger.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.