Sub topic 2
Storing a Tree in an Array with Index Arithmetic
This chapter assumes you can write Python functions and loops, that you know zero-based array indexing, and that you remember from the previous chapter what a complete binary tree is. Here you will see how such a tree fits into a plain list with no pointers, and how to move between nodes using arithmetic alone.
Level-Order Layout
A complete binary tree fills every level from left to right before it starts the next one. Because of that, you can write its nodes into an array in level order (root first, then the second level from left to right, and so on) and leave no gaps. The array position of each node is called its index.
Take the array [10, 4, 7, 1, 3, 9]. Index 0 holds the root. Indices 1 and 2 hold the second level. Indices 3, 4, and 5 hold the third level.
The Index Formulas
Each level holds twice as many nodes as the level above it. That doubling gives three simple formulas for a node at index i:
| Relation | Formula | Example for i = 1 |
|---|---|---|
| Left child | `2 * i + 1` | 3 |
| Right child | `2 * i + 2` | 4 |
| Parent | `(i - 1) // 2` | 0 |
def parent(i):
return (i - 1) // 2
def left(i):
return 2 * i + 1
def right(i):
return 2 * i + 2
a = [10, 4, 7, 1, 3, 9]
n = len(a)
for i in range(n):
kids = [a[c] for c in (left(i), right(i)) if c < n]
p = a[parent(i)] if i > 0 else None
print(f"i={i} value={a[i]} parent={p} children={kids}")Running this prints each node's parent and children. For example, index 2 (value 7) has parent 10 and the single child 9.
Which Nodes Are Leaves?
A node has no children when 2 * i + 1 >= n. Solving that inequality shows that the leaves fill indices n // 2 through n - 1. The last node with a child sits at index n // 2 - 1. For n = 6, that is index 2. Later chapters use this fact when building a heap, because only non-leaf nodes ever need fixing.
Common Errors
- Mixing one-based and zero-based formulas. Many textbooks store the root at index 1 and use
2i,2i + 1, andi // 2. Those formulas give wrong answers on a zero-based Python list. Pick one convention and stick to it. - Skipping the bounds check.
left(i)andright(i)can return indices past the end of the array. Always compare the result withn(or with the current heap size, which heap sort shrinks over time) before you read from it. - Using
/instead of//. In Python 3,(i - 1) / 2returns a float, and you cannot index a list with a float. - Calling
parent(0). The result is(0 - 1) // 2 == -1. Python acceptsa[-1]without complaint and quietly returns the last element. The root has no parent, so guard againsti == 0.
Why This Matters for Heap Sort
The array layout costs no extra memory for pointers. It also turns every move up or down the tree into a constant-time calculation. That is how heap sort runs in place with O(1) extra space: the tree exists only in how you interpret the indices.
Exercise
An array stores a complete binary tree with n = 10 elements. What is the parent index of node 7, and which children does node 4 have?
Show answer
The parent of 7 is (7 - 1) // 2 = 3. Node 4's left child is 2*4 + 1 = 9, which is valid because 9 < 10. Its right child would be 10, which is out of bounds (10 >= 10). So node 4 has only a left child, at index 9.
Exercise
For an array of length n = 11, what index range holds the leaves, and what is the index of the last non-leaf node?
Show answer
The leaves fill indices 11 // 2 = 5 through 10. The last non-leaf node is at index 5 - 1 = 4, and its left child is at 2*4 + 1 = 9, which is less than 11.