CJCoding With Joseph
15free / daySign inCreate account

Print a Heap in Level Order With Commas

Complete min_heap_print. It prints the values on one line in level order, inside square brackets, with a comma and a space between values. The later questions use this function to show you the heap.

Reminder: how this min heap is stored. A min_heap is a struct with three fields: capacity (the most values it can hold), count (how many it holds now) and values (a pointer to an array made with malloc). The heap is a complete binary tree kept in that array, filled row by row with no gaps, so only slots 0 to count - 1 are in use. Every parent is smaller than or equal to its children, so the smallest value is always at index 0. For the value at index i, the parent is at (i - 1) / 2 and the children are at 2 * i + 1 and 2 * i + 2.

Level order means: the root, then the second row from left to right, then the third row, and so on. Because the tree is stored row by row, level order is simply array order, from index 0 to count - 1.

          1
        /   \
       6     3
      / \
     8   7

index:   0   1   2   3   4
values:  1   6   3   8   7

printed:  an opening bracket, then  1, 6, 3, 8, 7  then a closing bracket

The comma is the tricky part: it goes BETWEEN values, so there is one fewer comma than values. A simple way is to print the comma before every value except the first.

Requirements: 1. Print [, then the values in use separated by a comma and one space, then ] and a newline. 2. No comma or space after the last value, and none before the first. 3. An empty heap prints [] and a newline. 4. Print only slots 0 to count - 1. Do not change the heap.

Do NOT write a main function.

Expected Output:

[2]
[2, 9, 5]
[2, 9, 5, 12, 10, 7]

= newline. The output ends with a newline — print one after the last line.

Hints4 available
Topics:
Data Structures & AlgorithmsHeaps
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Shift+Alt+F to format · Ctrl+Space to expand shortcuts (p, fori)

Your Output

Run your code to see the output here...

Test Cases

Run your code to see test case results.