Complete the code to identify the parent index in a heap array.
parent_index = (child_index - 1) [1] 2
In a heap represented as an array, the parent index of a child at index child_index is calculated by integer division of (child_index - 1) by 2.
Complete the code to find the left child index in a heap array.
left_child_index = [1] * 2 + 1
The left child of a node at parent_index in a heap array is at 2 * parent_index + 1.
Fix the error in the heapify function to correctly swap elements when the child is greater than the parent.
if heap[[1]] > heap[parent]: heap[[1]], heap[parent] = heap[parent], heap[[1]]
To maintain the heap property, we compare the child node's value with the parent's. If the child is greater, we swap the child and parent. So, the index to check is the child's.
Fill both blanks to complete the heapify condition that checks if the left child exists and is greater than the parent.
if [1] < len(heap) and heap[[2]] > heap[parent]:
The condition first checks if the left child index is within the heap size, then compares the left child's value with the parent's value.
Fill all three blanks to complete the dictionary comprehension that maps each node to its heapified value if it is greater than zero.
heapified = [1]: [2] for [1], [2] in enumerate(heap) if [2] > 0}
This comprehension creates a dictionary where each index maps to its value from the heap, but only includes values greater than zero.