Sub topic 4
Linked and array representations
This chapter assumes you know the tree vocabulary (root, parent, child, leaf, height) and the difference between full, complete, perfect, and skewed binary trees. It also assumes you can read basic Python and follow recursion. Here we look at how a binary tree is stored in memory, which index and pointer formulas GATE questions rely on, and where each representation wastes space.
Two ways to store a tree
A binary tree can be stored in two ways:
- Linked representation. Each node is an object holding a key and references to its children.
- Array representation. Nodes sit in one array, and a node's position determines where its children and parent are. No pointers are stored.
The shape of the tree decides which one is better. Complete trees fit arrays well. Sparse or skewed trees fit linked nodes well.
Linked representation
Each node stores a key, a left reference, and a right reference. A missing child is None (NULL in C). This is the Node class used in the traversal and BST code of the later chapters.
Some designs add a parent pointer to each node. It lets you move upward without recursion or a stack. That helps with finding a successor or deleting a node, but it costs one more pointer per node, and every insertion and rotation must keep it correct.
Counting null pointers
This count is a standard GATE question. A binary tree with n nodes has 2n child pointers. Every node except the root has exactly one parent, so exactly n - 1 pointers are non-null. The rest are null:
- null pointers =
2n - (n - 1) = n + 1
The result does not depend on the shape of the tree. A chain of 5 nodes and a perfect tree of 7 nodes both follow it: 6 and 8 null pointers.
For a tree where each node has k child slots, the same argument gives kn - (n - 1) = (k - 1)n + 1 null pointers.
Array representation
Store the root at one index and put the other nodes at positions computed from their parent. A missing node leaves a gap, usually marked None.
There are two indexing conventions. GATE questions usually use the 1-based one, but you must read the question to check which applies.
| Quantity | 1-based (root at 1) | 0-based (root at 0) |
|---|---|---|
| Left child of `i` | `2i` | `2i + 1` |
| Right child of `i` | `2i + 1` | `2i + 2` |
| Parent of `i` | `floor(i / 2)` | `floor((i - 1) / 2)` |
| Level of `i` (root is level 0) | `floor(log2 i)` | `floor(log2(i + 1))` |
Take the 1-based convention and a tree with array [50, 30, 70, -, 40, 60]. The key 40 is at index 5, its parent is at floor(5 / 2) = 2, and index 2 holds 30. That is correct: 40 is the right child of 30.
Why gaps appear
The array index of a node is determined by the path from the root. Each step left maps i to 2i + 1 and each step right maps it to 2i + 2. If a node has only one child, the other child's slot, and all slots below it, stay empty.
Space cost
Let the height h be counted in edges. The deepest node can sit at the last position of level h, so the array may need up to 2^(h+1) - 1 slots, even if the tree has few nodes.
- A perfect tree of height
hfills every slot, so there is no waste. - A complete tree of
nnodes fills slots0ton - 1with no gaps, so it needs exactlynslots. - A skewed tree with
nnodes has heightn - 1. In the worst case it needs2^n - 1slots to store onlynkeys.
A right-skewed chain of 4 nodes occupies indices 0, 2, 6, and 14, so it needs an array of length 15.
Index facts for complete trees
For a complete binary tree with n nodes in a 1-based array, the children of i exist only if their indices do not exceed n. This gives several facts that GATE questions use:
- Node
ihas a left child if2i <= n, and a right child if2i + 1 <= n. - Node
iis a leaf if2i > n. - The last internal node is at index
floor(n / 2), so a complete tree hasfloor(n / 2)internal nodes andceil(n / 2)leaves. - The leaves occupy indices
floor(n / 2) + 1throughn.
Check with n = 6. Internal nodes are at indices 1, 2, 3 (three of them), and leaves are at 4, 5, 6 (three of them). Node 3 has a left child at index 6, but no right child, because index 7 exceeds n.
These facts are the reason a binary heap is stored in an array. A heap is a complete tree, so it never has gaps and needs no pointers.
Converting between the two forms
The following code converts a linked tree to a 0-based array with gaps, and back. Both functions are recursive, and both use the index formulas from the table.
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def to_array(root):
slots = {}
def walk(node, i):
if node is None:
return
slots[i] = node.key
walk(node.left, 2 * i + 1)
walk(node.right, 2 * i + 2)
walk(root, 0)
size = max(slots) + 1 if slots else 0
return [slots.get(i) for i in range(size)]
def from_array(a, i=0):
if i >= len(a) or a[i] is None:
return None
node = Node(a[i])
node.left = from_array(a, 2 * i + 1)
node.right = from_array(a, 2 * i + 2)
return node
root = Node(50)
root.left = Node(30)
root.right = Node(70)
root.left.right = Node(40)
root.right.left = Node(60)
arr = to_array(root)
print(arr) # [50, 30, 70, None, 40, 60]
copy = from_array(arr)
print(to_array(copy) == arr) # True
chain = Node(1)
chain.right = Node(2)
chain.right.right = Node(3)
chain.right.right.right = Node(4)
print(len(to_array(chain))) # 15The last line shows the skewed-tree waste: 4 keys need 15 slots.
One edge case is a node whose key is None. The array form uses None as the "no node" marker, so such a key would vanish on conversion. Use a separate sentinel if keys can be None.
General trees: left-child, right-sibling
An ordinary tree node can have any number of children. Storing a list of children in each node wastes space when most nodes have few children. The left-child, right-sibling form avoids this. Each node keeps two pointers:
leftpoints to its first (leftmost) child.rightpoints to its next sibling, the next child of the same parent.
This turns any rooted tree with n nodes into a binary tree with n nodes. The root of the result has no right child, because the root has no siblings. To find the 3rd child of a node, follow left once and then right twice.
This form explains a common GATE result. The number of binary trees on n nodes (Catalan) is larger than the number of ordered trees on n nodes, which is the Catalan number for n - 1. The extra binary trees are the ones where the root has a right child, and they have no counterpart in this mapping.
Choosing a representation
| Question | Linked | Array |
|---|---|---|
| Extra memory per node | Two pointers (and maybe a parent pointer) | None |
| Finding a parent | Needs a parent pointer or a search | One arithmetic step |
| Space for a complete tree | `n` nodes plus `2n` pointers | `n` slots |
| Space for a skewed tree | `n` nodes plus `2n` pointers | Up to `2^n - 1` slots |
| Inserting or deleting in the middle | Change a few pointers | Usually means moving whole subtrees to new indices |
| Cache behaviour | Nodes scattered in memory | Contiguous |
Common errors
- Mixing the index conventions. The formulas
2iand2i + 1apply only when the root is at index 1. With the root at index 0, they point to the wrong nodes. - Using
i / 2for the parent. The parent index needs integer division,floor(i / 2). - Applying the null-pointer count to the wrong tree. The
n + 1result is for a binary tree, with two pointer slots per node. Adding a parent pointer changes the number of pointers, but the count of null child pointers staysn + 1. - Assuming a gap-free array. Only complete trees have no gaps. Any other tree needs
Nonemarkers.
Exercise
A binary tree has 20 nodes. How many null child pointers does its linked representation have? For a complete binary tree with 20 nodes stored in a 1-based array, which index is the last internal node, and which indices hold the leaves?
Show answer
The null pointer count is n + 1 = 21 for any binary tree with 20 nodes. For the complete tree, the last internal node is at index floor(20 / 2) = 10, and the leaves are at indices 11 through 20 (ten leaves).
Exercise
In a 1-based array, a node is stored at index 13. Give the indices of its parent and of its children, and its level when the root is level 0. Then repeat for a 0-based array where the node is at index 13.
Show answer
1-based: parent floor(13 / 2) = 6, children 26 and 27, level floor(log2 13) = 3. 0-based: parent floor(12 / 2) = 6, children 27 and 28, level floor(log2 14) = 3.
Exercise
What is the smallest array length that can hold a right-skewed binary tree of 5 nodes using the 0-based formulas, and what fraction of the slots is used?
Show answer
The nodes sit at indices 0, 2, 6, 14, and 30, so the array needs length 31 (that is, 2^5 - 1). Only 5 of the 31 slots are used, about 16%.