Data Structures · Trees

Representing a binary tree

A binary tree is a drawing of nodes and edges, but a program has to store it in memory somehow. There are two standard ways: put the nodes in an array at positions computed from the tree's shape, or give each node pointers to its children. This page shows both, lets you build a tree and see it stored each way, and asks when each one is the better choice.

1. Sequential (array) representation

Number the positions in the tree level by level, left to right, starting with the root at index 0. Then every node's position can be computed from its parent's, so no pointers are needed:

left child of i  = 2i + 1
right child of i = 2i + 2
parent of i      = (i − 1) / 2  // integer division

A position with no node is left as an empty slot, marked with a special value such as −1. The array has to be long enough for the deepest position used.

Some books start the root at index 1 instead. Then the children of i are at 2i and 2i + 1, and the parent is at i / 2. Both work; just never mix them.

The same tree, two pictures. Each node is stored at its index. C has no left child, so index 5 is an empty slot.
Stop and think
In the figure, F is at index 6. Use the formula to find its parent. Then find the children of B.

Parent of 6 is (6 − 1) / 2 = 2, which is C. B is at index 1, so its children are at 2·1 + 1 = 3 (D) and 2·1 + 2 = 4 (E).

A heap is a binary tree that is always stored in an array. Why is the array such a good fit for a heap?

A heap is always a complete tree: every level is full except the last, which fills from the left. So there are never any gaps, the array is exactly n long, and moving to a parent or child is just arithmetic.

A skewed tree has 6 nodes, each one the right child of the one before. How long must its array be?

The right children sit at 0, 2, 6, 14, 30 and 62, so the array needs 63 slots to hold 6 nodes, and 57 of them are empty. In general a tree of height h may need up to 2h+1 − 1 slots.

2. Linked representation

Each node is a separate object holding its data and two pointers: one to its left child and one to its right child. A missing child is nullptr. The program only keeps a pointer to the root; everything else is reached by following pointers down.

struct Node {
    int data;
    Node* left;     // nullptr if there is no left child
    Node* right;    // nullptr if there is no right child

    Node(int value) : data(value), left(nullptr), right(nullptr) {}
};

Leaves have both pointers set to nullptr. Nodes can be anywhere in memory, and adding or removing one only changes a pointer or two.

Linked nodes. Each box is left pointer | data | right pointer. A slashed cell is nullptr.
Stop and think
With only left and right pointers, how would you find a node's parent?

You can't do it directly: you have to search from the root for the node whose left or right pointer points to it, which can take O(n). Programs that need parents often add a third pointer, Node* parent, at the cost of more memory and more pointers to keep correct.

A tree has n nodes. How many of its 2n child pointers are nullptr?

n + 1. There are n − 1 edges, and each edge uses one pointer, so 2n − (n − 1) = n + 1 pointers are null.

3. Which one to use?

ArrayLinked nodes
MemoryOne slot per position, including empty ones: from n up to 2h+1 − 1 slotsExactly n nodes, each with two pointers of extra space
Find childrenO(1): compute 2i + 1 and 2i + 2O(1): follow left or right
Find parentO(1): compute (i − 1) / 2O(n) search, unless you add a parent pointer
Insert or delete a nodeEasy at the end; anything that changes the shape may mean moving many entries or growing the arrayChange a few pointers
Best forComplete trees: heaps and priority queuesTrees whose shape changes: binary search trees, expression trees, most general trees

4. Build a tree, see it stored both ways

Click a node in the tree, a cell in the array, or a box in the linked view: the same node is highlighted in all three, with its parent and children marked. Use the buttons to add children or delete a subtree, and watch the array grow and fill with gaps.

Presets

The tree

Selected node

As an array (root at index 0)

selectedparentchildrenempty slot

As linked nodes

5. Converting linked nodes to an array

This function copies a linked tree into an array. It is called with the root and index 0. Each node writes itself at index i, then passes 2i + 1 to its left child and 2i + 2 to its right child. The array grows as needed, and any slot no node writes to keeps the value EMPTY.

The tree you built

arr

Call stack

    What is happening

    toArray.cpp

      Each call needs to know its own index i, because nothing in the node itself says where it belongs.

      Stop and think
      The calls happen in preorder (node, left, right), not level by level. Why does the array still come out in level order?

      Where a node goes depends only on the index passed to it, not on when it is visited. Any traversal that passes the right index to each child fills the same slots; preorder is just the easiest to write recursively.

      How would you go the other way, building linked nodes from an array?

      Write a function build(arr, i) that returns nullptr if i is past the end or arr[i] is EMPTY; otherwise it makes a node for arr[i] and sets its left to build(arr, 2i + 1) and its right to build(arr, 2i + 2).