Binary Tree Array Implementation
A binary tree can be represented using an array, where each node's position is calculated using index arithmetic instead of explicit pointers. This representation is common for complete binary trees such as heaps.
Index Formulas
For a node stored at index i (0-based):
- Left child:
2*i + 1 - Right child:
2*i + 2 - Parent:
(i - 1) // 2
class ArrayBinaryTree:
def __init__(self, size):
self.tree = [None] * size
def insert(self, index, value):
if index >= len(self.tree):
self.tree.extend([None] * (index - len(self.tree) + 1))
self.tree[index] = value
def left_child(self, index):
left = 2 * index + 1
return self.tree[left] if left < len(self.tree) else None
def right_child(self, index):
right = 2 * index + 2
return self.tree[right] if right < len(self.tree) else None
def parent(self, index):
if index == 0:
return None
return self.tree[(index - 1) // 2]
Advantages
- No pointer/reference overhead — child and parent lookups are simple arithmetic.
- Cache-friendly due to contiguous memory storage.
- Ideal for complete binary trees, such as binary heaps.
Disadvantages
- Wastes memory for sparse or unbalanced trees, since empty slots must still be allocated.
- Resizing the array can be costly if the tree grows dynamically.
Applications
- Binary Heap implementation (min-heap / max-heap).
- Segment trees and Fenwick trees.
- Efficient priority queues.
Worked Example: Placing a Tree Into an Array
Consider this tree: A is the root, B and C are its children, B has children D and E, and C has only a right child F. Filling the array level by level, left to right, and leaving a gap where a child is missing gives:
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| Value | A | B | C | D | E | None | F |
Check the formulas against it. C sits at index 2, so its left child is at 2 × 2 + 1 = 5 (empty) and its right child at 6, which holds F. The parent of E at index 4 is (4 − 1) // 2 = 1, which is B. Every relationship comes from arithmetic alone.
Traversals Using Only Indexes
Because children are found by calculation, recursive traversals look almost the same as in a pointer-based tree. The only extra step is checking whether an index is inside the array and not empty.
tree = ["A", "B", "C", "D", "E", None, "F"]
def exists(i):
return i < len(tree) and tree[i] is not None
def inorder(i=0):
if not exists(i):
return []
return inorder(2 * i + 1) + [tree[i]] + inorder(2 * i + 2)
def preorder(i=0):
if not exists(i):
return []
return [tree[i]] + preorder(2 * i + 1) + preorder(2 * i + 2)
def level_order():
return [v for v in tree if v is not None]
print(inorder()) # ['D', 'B', 'E', 'A', 'C', 'F']
print(preorder()) # ['A', 'B', 'D', 'E', 'C', 'F']
print(level_order()) # ['A', 'B', 'C', 'D', 'E', 'F']
Level-order traversal is especially simple: it is just a left-to-right scan of the array, skipping empty slots. In a linked tree you would need a queue to do the same thing.
The 1-based variant
Some textbooks leave index 0 unused and store the root at index 1. The formulas then become left = 2i, right = 2i + 1 and parent = i // 2. Both versions are correct; just never mix them in one program.
Array or Linked Nodes: How to Decide
- Choose an array when the tree stays complete or nearly complete, as in heaps, or when you need fast parent lookups.
- Choose linked nodes when the tree is skewed, changes shape often, or needs subtrees moved around, as in binary search trees with rotations.
- A tree of height h may need up to 2^(h + 1) − 1 slots in the worst case. A tree that leans entirely to the right with only 10 nodes would need over a thousand slots, nearly all empty.
Frequent Bugs and a Short Checklist
- Using 1-based formulas on a 0-based array, which silently links the wrong nodes.
- Reading a child index without checking the array length first, causing an index error.
- Treating
0or an empty string as "no node". Use a clear marker such asNone. - Deleting a node by removing it from the list, which shifts every later index and breaks the whole structure. Set the slot to empty instead.
Before you commit to this representation: confirm the indexing base, decide your empty marker, estimate how sparse the tree can get, and test the parent and child formulas on a small example like the one above.