0

I am working with heaps and I am unsure if this is the right category to post this question in, but the question is:

Insert the keys 2 4 5 1 3 6 in that order into a heap. Draw the result.

I have draw the heap (I have attached the image), but I am unsure, if I have drawn it correctly according to the question.

Drawn heap here

Piqka
  • 43
  • 7

1 Answers1

1

Not sure your image is correct. Let's build the heap as items are entered.

When you insert 2, it becomes the root. Adding 4 will make 4 the root and 2 has to go to the left subtree in order to satisfy the shape property. So you have in your array, [4, 2].

Now you add 5 to the end of the array and bubble it up. That results in [5, 4, 2]. Adding 1 gives you [5, 4, 2, 1]. That tree representation is:

        5
    /       \
   4         2
  /
 1

Now, when you add 3 you get [5, 4, 2, 1, 3]. The parent of 3 is 4, so there's no need to bubble it up, and you get:

        5
     /     \
    4       2
   / \
  1   3

Finally, you add 6 to the array and get [5, 4, 2, 1, 3, 6]. You need to bubble 6 up. The parent of 6 is 2, so on the first pass of bubbling it up you get [5, 4, 6, 1, 3, 2], and bubbling up again gives you [6, 4, 5, 1, 3, 2]. The tree representation is:

        6
     /     \
    4       5
   / \     /
  1   3   2
Jim Mischel
  • 131,090
  • 20
  • 188
  • 351