Array Implementation of Trees
Binary trees don't have to be built from node objects with left and right references. A binary tree can also be stored in a plain array, level by level, from left to right. No pointers are needed: the position of a node tells you where its children and parent are.
A index: 0 1 2 3 4 5 6
/ \ value: [A, B, C, D, E, F, G]
B C
/ \ / \
D E F GThe index formulas
With the root at index 0, for the node at index i:
| Relative | Index |
|---|---|
| left child | 2 * i + 1 |
| right child | 2 * i + 2 |
| parent | (i - 1) // 2 |
A child index that is past the end of the array means "no child".
tree = ["A", "B", "C", "D", "E", "F", "G"]
def left(i): return 2 * i + 1
def right(i): return 2 * i + 2
def parent(i): return (i - 1) // 2
for i, value in enumerate(tree):
kids = [tree[c] for c in (left(i), right(i)) if c < len(tree)]
up = tree[parent(i)] if i > 0 else "-"
print(f"{i}: {value} parent {up} children {kids}")0: A parent - children ['B', 'C']
1: B parent A children ['D', 'E']
2: C parent A children ['F', 'G']
3: D parent B children []
4: E parent B children []
5: F parent C children []
6: G parent C children []
Traversals with indexes
All the traversals from the previous lessons work the same way; recursion just follows index arithmetic instead of references. Level-order traversal is simply reading the array from left to right!
tree = ["A", "B", "C", "D", "E", "F", "G"]
def preorder(i=0):
if i >= len(tree):
return []
return [tree[i]] + preorder(2 * i + 1) + preorder(2 * i + 2)
def inorder(i=0):
if i >= len(tree):
return []
return inorder(2 * i + 1) + [tree[i]] + inorder(2 * i + 2)
def postorder(i=0):
if i >= len(tree):
return []
return postorder(2 * i + 1) + postorder(2 * i + 2) + [tree[i]]
print("pre: ", " ".join(preorder()))
print("in: ", " ".join(inorder()))
print("post: ", " ".join(postorder()))
print("level:", " ".join(tree))pre: A B D E C F G
in: D B E A F C G
post: D E B F G C A
level: A B C D E F G
Gaps waste space
If a node is missing, its slot (and the slots of all its would-be descendants) must still exist, marked with None. For complete trees there are no gaps. For unbalanced trees the array can be mostly empty:
# The tree A
# \
# C
# \
# G stored by position:
sparse = ["A", None, "C", None, None, None, "G"]
def preorder(tree, i=0):
if i >= len(tree) or tree[i] is None:
return []
return [tree[i]] + preorder(tree, 2 * i + 1) + preorder(tree, 2 * i + 2)
print(preorder(sparse))
used = sum(v is not None for v in sparse)
print(f"{used} nodes in {len(sparse)} slots")
depth = 20
print(f"a right-only chain of depth {depth} needs {2 ** (depth + 1) - 1:,} slots")['A', 'C', 'G']
3 nodes in 7 slots
a right-only chain of depth 20 needs 2,097,151 slots
So arrays are ideal for complete binary trees (every level full except the last, filled from the left), and a poor choice for trees that can become lopsided, like an unbalanced binary search tree.
The most famous array tree: the binary heap
A binary heap is always a complete tree, so it is always stored in an array. In a min-heap every parent is smaller than or equal to its children, so the minimum sits at index 0. Watch the array (shown after each step) and the tree it represents:
Adding a value appends it at the end of the array (the next free spot in the last level) and then sifts it up: while it is smaller than its parent at (i - 1) // 2, the two swap.
heap = []
def push(value):
heap.append(value)
i = len(heap) - 1
while i > 0 and heap[(i - 1) // 2] > heap[i]:
p = (i - 1) // 2
heap[p], heap[i] = heap[i], heap[p]
i = p
print(f"push {value:>2}: {heap}")
for v in [18, 9, 25, 4, 12]:
push(v)push 18: [18]
push 9: [9, 18]
push 25: [9, 18, 25]
push 4: [4, 9, 25, 18]
push 12: [4, 9, 25, 18, 12]
The arrays printed here are the same as in the animation's notes. The Heaps & Priority Queues lesson adds removal of the minimum and heap sort.
Pros and cons
| Array representation | Node objects | |
|---|---|---|
| Memory per node | just the value | value + two references |
| Find parent | O(1), free |
needs an extra parent reference |
| Cache friendliness | excellent (contiguous) | poor (scattered) |
| Unbalanced trees | wasteful gaps | fine |
| Insert/delete in the middle | expensive (moves subtrees) | cheap (relink) |
Test yourself
With the root at index 0, where are the children of the node at index 3?
- 4 and 5
- 6 and 7
- 7 and 8
- 3 and 4
What is the parent index of the node at index 6?
- 2
- 3
- 5
- 12
Which trees are best suited to array storage?
- Degenerate trees
- Complete binary trees
- Trees with many children per node only
- Unbalanced search trees