Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Trees and hierarchy
EXPERIMENT 31 / 66

Store the tree without the pointers.

Use index arithmetic for compact complete-tree layouts and know where it wastes space.

BY NAVAN SAMI◷ 7 MIN READCORESTRUCTURE

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.

THE THING THAT MUST STAY TRUE

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.

the_strategy.txt
COMPUTE possible child indices
CHECK whether each lies inside the stored layout
READ only valid child positions

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

array_trees.py
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)
↳ EXPECTED OUTPUT
A ['B', 'C']
B ['D', 'E']
C []
D []
E []
  1. 1

    The fixture is a complete tree whose last level is filled from the left. It has no gaps before its final element.

  2. 2

    Always check bounds before reading a possible child. An index formula can describe a position that the current tree does not contain.

  3. 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

TIME

O(1) parent/child index calculation; O(n) listing

SPACE

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

A SMALL MISSION

Find the parent of the element at index 4.

Reveal one possible solution +
one_possible_solution.py
tree = ["A", "B", "C", "D", "E"]
index = 4
print(tree[(index - 1) // 2])

06 Check your reasoning

QUICK SIGNAL CHECK

What is the left child index of zero-based position i?

ANOTHER PATTERN IN YOUR TOOLKIT.

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.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.