What are the strengths and the weakness of storing a binary tree in an array?
Strengths: no references to store, and every child or parent is found by index arithmetic in $O(1)$. Weakness: the array needs a slot for every rank up to the highest one, so an unbalanced tree wastes enormous amounts of space โ up to $2^n$ slots for $n$ nodes.
The rank of a node depends on its position in the tree, not on how many nodes exist. Each level down doubles the rank. So:
- A tree where every level is filled from left to right (a complete tree) uses the ranks $1 \dots n$ without gaps. The array is packed and the layout is ideal.
- A tree that degenerates into a chain of right children has ranks $1, 3, 7, 15, \dots, 2^n - 1$. Storing $n$ nodes then needs an array of about $2^n$ slots, almost all of them empty.
Every missing node in the middle of the tree leaves a hole, and so do all of its would-be descendants.
A typical implementation keeps the array length at a power of two and doubles it whenever a child's rank falls beyond the end, the same growth strategy as an array-list.
Tip: use the array layout when the tree is guaranteed to stay complete, as a heap is. Use linked nodes when the shape is unpredictable.