Sub topic 4
Representing Binary Trees in Memory
This chapter assumes basic programming with functions and recursion, object references, arrays, linked lists, and Big-O notation. A binary tree is a collection of nodes where each node has at most two children: a left child and a right child. The representation determines how those nodes and child relationships are stored.
Linked representation
In a linked representation, each node stores its value and references to its children. A missing child is represented by None or a null pointer. The tree itself is usually represented by a reference to its root node.
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
root = Node(8)
root.left = Node(3)
root.right = Node(10)
root.left.right = Node(6)The structure is:
8
/ \
3 10
\
6A linked representation works for any binary tree, including a sparse tree. It allocates space only for nodes that exist. To reach a node, however, the program follows references from the root. Accessing an arbitrary node therefore takes time related to its depth.
Array representation
An array can represent a binary tree by placing nodes at positions determined by their relationships. With zero-based indexing, store the root at index 0. For a node at index i:
| Relationship | Array index |
|---|---|
| Node | `i` |
| Left child | `2i + 1` |
| Right child | `2i + 2` |
| Parent, when `i > 0` | `(i - 1) // 2` |
For example, this complete tree uses the first seven positions:
tree = [8, 3, 10, 1, 6, 9, 14]
i = 1 # node 3
left_child = tree[2 * i + 1] # 1
right_child = tree[2 * i + 2] # 6The formulas are convenient because they avoid storing explicit child references. They are especially useful for complete binary trees, such as binary heaps. In a complete tree, nodes fill each level from left to right, so the array has little unused space.
Choosing a representation
Linked storage is usually the better choice for an arbitrary binary search tree. Inserting or deleting a node changes references rather than shifting many array elements. It also avoids reserving positions for missing nodes.
Array storage is efficient when the shape is known to be complete or nearly complete. For a sparse tree, the array may contain many empty positions. Consider a tree that has only a root and a deep right child. The child’s index grows quickly, even though only two nodes exist.
| Tree shape | Usually suitable representation |
|---|---|
| Complete binary tree or heap | Array |
| Sparse or irregular binary tree | Linked nodes |
| Binary search tree with frequent updates | Linked nodes |
Exercise
In a zero-based array representation, where are the children of the node at index 4 stored?
Show answer
The left child is at index 2(4) + 1 = 9, and the right child is at index 2(4) + 2 = 10.