Sub topic 3
Storing a heap in an array
This chapter assumes you know Python lists, zero-based indexing, basic binary tree terms (parent, child, depth) and Big-O notation. It also assumes you know the heap property from the previous chapter: every parent is less than or equal to its children in a min-heap.
Why an array works
A binary heap is a complete binary tree. Every level is full except possibly the last, and the last level fills from left to right. Because there are no gaps, you can list the nodes level by level in a plain list. No node objects or pointers are needed.
Take this min-heap:
- Level 0: 1
- Level 1: 3, 2
- Level 2: 7, 4, 5
Reading level by level gives the list [1, 3, 2, 7, 4, 5].
Index arithmetic
With zero-based indexes, the relatives of the node at index i are:
| Relation | Formula |
|---|---|
| Parent | `(i - 1) // 2` |
| Left child | `2 * i + 1` |
| Right child | `2 * i + 2` |
Check with the example. The node 4 is at index 4. Its parent is (4 - 1) // 2 = 1, which holds 3. The node 3 at index 1 has children at indexes 3 and 4, which hold 7 and 4.
A child index only exists if it is smaller than the list length n. Always test child < n before reading it.
def parent(i):
return (i - 1) // 2
def left(i):
return 2 * i + 1
def right(i):
return 2 * i + 2
heap = [1, 3, 2, 7, 4, 5]
n = len(heap)
for i in range(n):
kids = [heap[c] for c in (left(i), right(i)) if c < n]
print(f"index {i}: value {heap[i]}, children {kids}")Running this prints each node with its children. The last three nodes have an empty list, because they are leaves.
Why the shape matters
The compact layout depends on the tree being complete. If a node could be missing in the middle of a level, the formulas would point to the wrong slots, and you would need placeholders for the gaps.
Completeness gives two more facts you will use in later chapters:
- A heap with
nitems has heightfloor(log2(n)). This is why insert and extract cost O(log n). - The last item is always at index
n - 1. Appending to the list adds the next free leaf position, andlist.pop()removes the last leaf. Both are O(1) amortized.
The leaves occupy indexes n // 2 through n - 1. Any index below n // 2 has at least one child. In the example, n = 6, so indexes 3, 4 and 5 are leaves.
Common errors
- Using one-based formulas. Many textbooks put the root at index 1 and use
2iand2i + 1. Those formulas are wrong for a Python list that starts at 0. - Forgetting the bounds check. Reading
heap[2 * i + 2]without checking< nraisesIndexErrornear the bottom of the heap. - Assuming the list is sorted. The array is only ordered between parents and children.
[1, 3, 2, 7, 4, 5]is a valid heap, but siblings and cousins have no required order. For example,3comes before2.
Exercise
A min-heap is stored as [2, 5, 3, 9, 6, 8, 4]. What are the indexes and values of the parent and both children of the node at index 2? Which indexes are leaves?
Show answer
The node at index 2 holds 3. Its parent is (2 - 1) // 2 = 0, which holds 2. Its left child is 2 2 + 1 = 5, which holds 8. Its right child is 2 2 + 2 = 6, which holds 4. With n = 7, the leaves are indexes 7 // 2 = 3 through 6, which hold 9, 6, 8 and 4.