Trees in an array

No references, just math · Part of Trees and graphs

Key idea

Practice

6 questions · about 3 min

Explained step by step

Binary tree

A perfect binary tree can be stored in an array by putting the nodes in level order: the root at index 0, its children at 1 and 2, its grandchildren from 3 to 6. With that order a formula appears: if a node is at index i, its left child is at 2i + 1 and its right child at 2i + 2. The formulas do the references' job: there's no need to store what each node points to.

With the same formulas, you can also go from a child to its parent: index i's parent is at (i − 1) / 2, rounded down. That way you can move up and down the tree with just math. This is used a lot in heaps, which store their tree in an array and move elements up and down all the time.

The formulas work if the tree is full. If it's missing nodes in the middle, storing it by levels shifts the spots and the formulas stop pointing to the right child. The fix is to store the gaps too: where a node is missing, put None. That way each node lands at the index it should, and the array identifies the tree without ambiguity.

Storing a tree in an array has advantages: memory is contiguous, so it's cache-friendly and fast to walk; no references need storing, which saves space; and you can reach any node by its index. And it has limits: it needs a big block of adjacent memory, inserting and deleting in the middle is expensive, and if the tree has many gaps, space is wasted.

Balanced tree

Complete binary trees are the ones that fit best in an array. Since in a complete tree only the end of the last level can be missing, all the gaps end up at the end of the array, and they can be left out. Not a single None in the middle: the array has exactly n slots. That's why heaps, which are complete trees, are always stored in an array.

Breadth-first search (BFS)

Since the array stores the tree by levels, reading it left to right is already the level-order traversal: no queue needed. The other traversals, like preorder or inorder, work the same as with nodes, but instead of following references you compute the children's indexes with 2i + 1 and 2i + 2, and skip the None entries.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

No references, just math