Sub topic 2
Storing a Tree in an Array with Index Arithmetic
This chapter assumes you can write Python loops and functions, that you are comfortable with zero-based array indexing, and that you know what a complete binary tree is from the previous chapter. You will learn how to store that tree in a plain array with no pointers. You will also learn how to move between parent and child using only arithmetic, and how to avoid the off-by-one mistakes that this arithmetic often causes.
Why an Array Instead of Nodes and Pointers
A linked binary tree stores each node as an object with a value and two references to its children. That works, but it costs memory for every reference, and it scatters nodes across the heap of your process. Heap sort is meant to sort an array in place, using only a constant amount of extra memory. If we had to build a linked tree first, we would lose that property.
The fix is to treat the array itself as the tree. No extra structure is created. The tree is only a way of reading the array: certain index pairs count as "parent and child" because of a fixed formula. This works only because the tree is complete. Every level is full except possibly the last, and the last level fills from the left. So there are never gaps, and every index from 0 to n - 1 holds exactly one node.
Level-Order Layout
The layout rule is simple. Write the nodes down level by level, from top to bottom, and left to right within each level. The root goes to index 0, its two children go to indices 1 and 2, the four grandchildren to 3 through 6, and so on.
Take the array [9, 7, 8, 3, 5, 6]. Read in level order, it describes this tree:
Each level k (with the root at level 0) holds up to 2^k nodes, and the levels sit next to each other in the array:
| Level k | Max nodes | First index | Last index |
|---|---|---|---|
| 0 | 1 | 0 | 0 |
| 1 | 2 | 1 | 2 |
| 2 | 4 | 3 | 6 |
| 3 | 8 | 7 | 14 |
| k | 2^k | 2^k − 1 | 2^(k+1) − 2 |
The "first index" column follows from summing the sizes of all earlier levels: 1 + 2 + 4 + ... + 2^(k-1) = 2^k - 1.
The Index Formulas
For a zero-indexed array, the relationships are:
def parent(i):
return (i - 1) // 2
def left(i):
return 2 * i + 1
def right(i):
return 2 * i + 2Deriving the Child Formula
You don't have to memorize these formulas. Suppose node i is the j-th node (counting from 0) on level k. Then i = 2^k - 1 + j.
Every node to its left on level k has two children on level k + 1, and those children come before node i's children. So node i's left child is at position 2j on level k + 1, giving index:
2^(k+1) - 1 + 2j = 2 * (2^k - 1 + j) + 1 = 2i + 1The right child sits immediately after it, at 2i + 2.
Deriving the Parent Formula
The parent formula reverses both child formulas at once. If c = 2i + 1 then (c - 1) // 2 = i. If c = 2i + 2 then (c - 1) // 2 = (2i + 1) // 2 = i, because floor division throws away the .5. One expression handles both the left child and the right child.
You can confirm that the formulas agree with each other over a large range:
def parent(i):
return (i - 1) // 2
def left(i):
return 2 * i + 1
def right(i):
return 2 * i + 2
for i in range(100_000):
assert parent(left(i)) == i
assert parent(right(i)) == i
assert right(i) == left(i) + 1
print("index formulas are consistent")Bounds: Which Children Actually Exist
The formulas always return a number, but that number may point past the end of the array. In an array of length n, a child index c is real only if c < n. This one check is the source of most heap bugs.
From the bounds rule we get two facts that later chapters depend on:
- Node
ihas at least one child exactly when2i + 1 < n, which simplifies toi < n // 2(equivalently,i <= n // 2 - 1). - So indices
0throughn // 2 - 1are internal nodes, and indicesn // 2throughn - 1are leaves. About half of the array is leaves.
At most one node has exactly one child. That happens when n is even, and the node is n // 2 - 1, whose right child would sit at index n.
In the example, n = 6. Internal nodes are indices 0, 1 and 2, and leaves are 3, 4 and 5. Index 2 has only a left child (index 5), because its right child would be index 6.
Depth and Height from an Index
The level of index i is floor(log2(i + 1)). Integer bit operations compute this exactly, with no floating-point rounding:
def depth(i):
return (i + 1).bit_length() - 1
def height(n):
# Height of a complete binary tree with n >= 1 nodes.
return n.bit_length() - 1
print([depth(i) for i in range(8)]) # [0, 1, 1, 2, 2, 2, 2, 3]
print(height(6), height(7), height(8)) # 2 2 3The height is floor(log2 n). This is why any path from the root to a leaf has O(log n) steps, and that is the bound behind the cost of sift-down in the next chapters.
Putting It Together
This program walks the example array and prints each node's relationships using only index arithmetic:
def parent(i):
return (i - 1) // 2
def left(i):
return 2 * i + 1
def right(i):
return 2 * i + 2
def depth(i):
return (i + 1).bit_length() - 1
def describe(a):
n = len(a)
for i, value in enumerate(a):
kids = [a[c] for c in (left(i), right(i)) if c < n]
p = a[parent(i)] if i > 0 else None
print(f"index {i}: value={value} depth={depth(i)} parent={p} children={kids}")
describe([9, 7, 8, 3, 5, 6])Output:
index 0: value=9 depth=0 parent=None children=[7, 8]
index 1: value=7 depth=1 parent=9 children=[3, 5]
index 2: value=8 depth=1 parent=9 children=[6]
index 3: value=3 depth=2 parent=7 children=[]
index 4: value=5 depth=2 parent=7 children=[]
index 5: value=6 depth=2 parent=8 children=[]Zero-Based vs. One-Based Formulas
Many textbooks, including CLRS, use one-based arrays. There the formulas are shorter:
| Relationship | Zero-based (Python, C, Java) | One-based (textbook) |
|---|---|---|
| Root | 0 | 1 |
| Parent of i | (i − 1) // 2 | i // 2 |
| Left child of i | 2i + 1 | 2i |
| Right child of i | 2i + 2 | 2i + 1 |
| Last internal node | n // 2 − 1 | n // 2 |
| First leaf | n // 2 | n // 2 + 1 |
The one-based version has a neat bit-level reading. Moving to a left child appends a 0 bit to the index, moving to a right child appends a 1, and moving to the parent drops the last bit. The binary form of a one-based index therefore spells out the path from the root. Some implementations leave slot 0 of the array unused to get these simpler formulas, at the cost of one wasted cell.
Common Errors and Gotchas
Asking for the Root's Parent
In Python, parent(0) evaluates (0 - 1) // 2, which is -1, because // rounds toward negative infinity. Index -1 is legal in Python and silently refers to the last element. In C or Java, integer division truncates toward zero, so (0 - 1) / 2 is 0, and the root becomes its own parent. Neither language raises an error. Always guard with i > 0 before you use a parent index.
Checking Only the Left Child
A node can have a left child without a right one. Code that checks left(i) < n and then reads a[right(i)] will go one past the end when n is even. Check each child index separately.
Using the Full Array Length Instead of the Heap Size
During heap sort, the array is split into a heap part at the front and a sorted part at the back. The bound in the bounds check must be the current heap size, not len(a). If you compare against len(a), the sorted tail gets pulled back into the heap. This is why the sift_down function in later chapters takes an explicit end parameter.
Overflow in Fixed-Width Languages
In C or Java, 2 * i + 1 can overflow when i is above about half the maximum integer value. Python integers have no size limit, but in other languages you should keep indices in a type wide enough for 2n.
Exercises
Exercise
In a zero-indexed heap array, what are the parent, left child and right child indices of node 10?
Show answer
Parent is (10 - 1) // 2 = 4. Left child is 210 + 1 = 21. Right child is 210 + 2 = 22. Those children exist only if the array has at least 22 or 23 elements.
Exercise
An array has 11 elements. Which index is the last internal node, and which indices are leaves? Check your answer with the child formula.
Show answer
The last internal node is 11 // 2 - 1 = 4. Its left child is 9 and its right child is 10, both less than 11. Index 5 would have left child 11, which is out of range, so indices 5 through 10 are leaves.
Exercise
Starting from the one-based formulas (parent i // 2, children 2i and 2i + 1), derive the zero-based formulas by substituting i = j + 1, where j is the zero-based index.
Show answer
The left child in one-based terms is 2(j + 1) = 2j + 2. Subtract 1 to convert back to zero-based: 2j + 1. The right child is 2(j + 1) + 1 - 1 = 2j + 2. The parent is (j + 1) // 2 - 1 = (j + 1 - 2) // 2 = (j - 1) // 2.
Exercise
A colleague's Python sift-down calls a[parent(i)] without checking i > 0. What happens when i is 0, and why does it raise no error?
Show answer
parent(0) evaluates (0 - 1) // 2, which is -1 because Python's floor division rounds toward negative infinity. a[-1] is a valid Python index meaning the last element, so the code silently compares the root with the last element instead of failing.