Sub topic 4
Storing a binary tree in an array
This chapter assumes you know zero-based indexing, basic recursion, and what a binary tree is. Segment trees and Fenwick trees both keep their nodes in a flat list instead of linked node objects. This chapter shows the index arithmetic that makes that work.
Index arithmetic instead of pointers
A linked tree needs an object with left and right references for every node. An array-backed tree computes those links from the index. Number the root 1 and number each level left to right. The rules are:
| Relation | Index |
|---|---|
| Left child of `i` | `2 * i` |
| Right child of `i` | `2 * i + 1` |
| Parent of `i` | `i // 2` |
The root must be 1, not 0. With 0 as the root, 2 * 0 is 0, so the root would be its own left child.
Seeing the layout
This script uses the same recursion as the segment tree and records which segment each index holds.
def layout(lo, hi, node, out):
out[node] = (lo, hi)
if lo == hi:
return
mid = (lo + hi) // 2
layout(lo, mid, 2 * node, out)
layout(mid + 1, hi, 2 * node + 1, out)
out = {}
layout(0, 4, 1, out)
for node in sorted(out):
print(node, out[node])
print("max index:", max(out))The output lists nodes 1 through 9, for example 4 (0, 1) and 9 (1, 1), and ends with max index: 9. The array indices match the diagram.
Why the array has 4n slots
A tree built over 5 elements uses indices up to 9, but the array must be sized for the worst case. The recursion splits segments unevenly when n is not a power of two, so some leaves sit one level deeper than others. The deepest level can hold indices up to 2^(ceil(log2 n) + 1) - 1. That value is always less than 4n. Allocating 4 * n slots is a safe bound.
Some indices in the array are never used. In the example, indices 10 through 19 stay empty, and so does index 0. That wasted space is the price of using the simple 2 * i rule on an unbalanced shape.
Common mistakes
- Starting the root at 0. The child formulas then break.
- Allocating only
2 * nslots for the recursive tree. This works whennis a power of two and raisesIndexErrorfor other sizes. - Mixing index meanings. A node index such as 5 is a position in the tree array. It has no relation to the array position 5 in your data. The tree stores each node's segment
[lo, hi]implicitly, by passing it down the recursion.
Exercise
In a 1-indexed array-backed binary tree, what are the parent and the two children of node 11?
Show answer
The parent is 11 // 2 = 5. The left child is 2 11 = 22 and the right child is 2 11 + 1 = 23.