Sub topic 17
Storing a binary tree in an array
This chapter assumes you know the Node class from earlier, level-order traversal, and basic Big-O. It shows how to store a binary tree in a plain list with no node objects and no pointers.
Index arithmetic replaces pointers
A node-based tree stores links in left and right. An array-based tree stores each value at an index that is computed from its position. Number the nodes level by level, left to right, starting at 0. This is the same order that level-order traversal visits them.
For a node at index i:
| Relation | Index |
|---|---|
| Left child | `2*i + 1` |
| Right child | `2*i + 2` |
| Parent | `(i - 1) // 2` |
Some texts start at index 1. Then the children are 2*i and 2*i + 1, and the parent is i // 2. Pick one convention and keep it.
The array for this tree is [1, 2, 3, 4, 5].
Converting a tree to an array
A missing child still occupies a slot, so you mark it with None. This function writes each value at its computed index.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def to_array(root):
slots = {}
def fill(node, i):
if node is None:
return
slots[i] = node.value
fill(node.left, 2 * i + 1)
fill(node.right, 2 * i + 2)
fill(root, 0)
if not slots:
return []
return [slots.get(i) for i in range(max(slots) + 1)]
root = Node(1, Node(2, Node(4), Node(5)), Node(3))
chain = Node(1, None, Node(2, None, Node(3)))
print(to_array(root)) # [1, 2, 3, 4, 5]
print(to_array(chain)) # [1, None, 2, None, None, None, 3]Traversing the array directly
The traversal logic is unchanged. Only the child lookup differs.
def inorder_array(a, i=0):
if i >= len(a) or a[i] is None:
return []
return inorder_array(a, 2 * i + 1) + [a[i]] + inorder_array(a, 2 * i + 2)
print(inorder_array([1, 2, 3, 4, 5])) # [4, 2, 5, 1, 3]Level-order traversal needs no queue at all. You read the list from left to right and skip the None entries.
When this pays off
The layout suits complete trees, where every level is full except possibly the last, and the last level is filled from the left. Such a tree has no gaps, so n nodes use exactly n slots. Binary heaps rely on this property.
It wastes space on sparse trees. The right-leaning chain above has 3 nodes but needs 7 slots. A chain of n nodes needs about 2^n slots, so memory grows exponentially with depth.
Other trade-offs:
- Array storage has better cache locality and no per-node object overhead.
- Parent lookup is a constant-time formula, with no parent pointer needed.
- Inserting or deleting in the middle of the tree can force you to move many entries.
- Growing the array when the tree gets deeper means reallocating it.
Common errors
- Mixing the 0-based and 1-based formulas in one program.
- Forgetting the bounds check
i >= len(a)before reading a child. - Treating
len(a)as the node count when the array containsNonegaps.
Exercise
A complete binary tree is stored in a 0-based array with 15 entries. At what index is the parent of the node at index 11, and what are the indexes of the children of the node at index 5?
Show answer
The parent of index 11 is (11 - 1) // 2 = 5. The children of index 5 are 25 + 1 = 11 and 25 + 2 = 12.