CJCoding With Joseph
15free / daySign inCreate account

Find a Heap Node's Parent and Children

Complete the three index helpers parent(int i), leftChild(int i) and rightChild(int i) in this min heap. Each one takes the index of a node and returns the index of one of its relatives in the array.

Reminder: what a heap is. A heap is a complete binary tree stored in a plain array. The tree is filled row by row, left to right, with no gaps, so it needs no Node objects and no links: a node's position in the array is enough to find its parent and its children. In a min heap every parent is smaller than or equal to its children, which keeps the smallest value at index 0. A heap is NOT a binary search tree: it only promises the parent-child rule, so a left child can be bigger than its right sibling (9 and 7 below).

index:   0   1   2   3   4   5
value:   5   9   7  12  10   8

            5              row 1: index 0
          /   \
         9     7           row 2: index 1, 2
        / \   /
      12  10 8             row 3: index 3, 4, 5

Read the pattern off the picture and turn it into arithmetic on i.

Requirements: 1. leftChild(i) and rightChild(i) return the indexes of the two children of index i: index 0 has children 1 and 2, index 1 has children 3 and 4, index 2 has children 5 and 6. 2. parent(i) returns the index of the node directly above index i: indexes 1 and 2 lead to 0, indexes 3 and 4 lead to 1, indexes 5 and 6 lead to 2. It is only called with i greater than 0, because the root has no parent. 3. A child index may be past the end of the heap; describe(int i) already compares it with size before reading the array. 4. Leave the constructor, describe(int i) and toString() as they are. The constructor copies values that are already in heap order.

Do NOT write a main method.

Expected Output:

MinHeap: 2 6 3 11 8 4
1 3 4
2 5 6
6: parent 2, left 11, right 8
3: parent 2, left 4, right none

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

Hints3 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 (sysout, psvm, fori)

Your Output

Run your code to see the output here...

Test Cases

Run your code to see test case results.