Store the tree without the pointers.
Use index arithmetic for compact complete-tree layouts and know where it wastes space.
01 Model the idea
A complete binary tree can be represented compactly in an array. With zero-based indexing, a node at i has possible children at 2i+1 and 2i+2, and a nonroot node’s parent is at (i-1)//2. These are layout relationships, not key-order relationships. Sparse or highly skewed trees can leave many unused array positions.
Every stored child’s parent index matches the intended complete-tree layout.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
COMPUTE possible child indices
CHECK whether each lies inside the stored layout
READ only valid child positions03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
tree = ["A", "B", "C", "D", "E"]
for index, value in enumerate(tree):
left, right = 2 * index + 1, 2 * index + 2
children = [tree[i] for i in [left, right] if i < len(tree)]
print(value, children)A ['B', 'C'] B ['D', 'E'] C [] D [] E []
- 1
The fixture is a complete tree whose last level is filled from the left. It has no gaps before its final element.
- 2
Always check bounds before reading a possible child. An index formula can describe a position that the current tree does not contain.
- 3
Heaps use this layout plus a heap-order invariant. A binary search tree uses a different ordering invariant and may not have a compact complete shape.
04 Count the cost
O(1) parent/child index calculation; O(n) listing
O(n) compact complete-tree storage
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Find the parent of the element at index 4.
Reveal one possible solution +
tree = ["A", "B", "C", "D", "E"]
index = 4
print(tree[(index - 1) // 2])06 Check your reasoning
What is the left child index of zero-based position i?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.