AlgoFrames

Binary trees and how they are stored

In a binary tree each node has at most a left and a right child. See nodes as objects with references, and complete trees stored in an array.

Before you start: Trees: root, leaf, depth, height, subtree.

The idea

In a binary tree each node has at most two children, called left and right. How does a program keep such a tree in memory?

Left and right are positions, not just an order. A node with only a right child is a different tree from one with only a left child.

Intuition

Each node is an object in memory with a value and two references, left and right. A missing child is a null reference.

A reference is the address of another object. The variable root holds the address of the top node, @100.

A complete tree fills every level from left to right. It fits in a plain array, level by level, with no references.

The positions do the work of the references. The children of index i sit at 2i + 1 and 2i + 2.

Complexity

Both forms use O(n) space; node objects add two references each. Counting visits every node once: O(n) time, O(h) stack.

In the array, a child is found by arithmetic in O(1). With objects, the program follows a reference, also O(1), but each node costs extra memory.

Pitfalls

The array form only suits complete trees. A chain of 3 nodes going right needs 7 slots, and most of them stay empty.

Each level down doubles the index. A chain of n nodes would need about 2 to the power n slots, so such trees use node objects.

In the list [1, null, 2, 3, 4], the null keeps no slots for children it does not have. So 3 and 4 are the children of 2.

Problem sites list trees this way: only real nodes get children in the list. The 2i + 1 rule does not apply to this list form unless the tree is complete.

Variations

Binary heaps and segment trees keep complete trees in arrays. Search trees and expression trees use node objects.

Code

Pseudocode

build(arr)
  if arr is empty: return null
  root ← new Node(arr[0]); queue ← [root]; i ← 1
  while i < length(arr)
    p ← queue.dequeue()
    for side in (left, right)
      if i < length(arr) and arr[i] ≠ null
        p.side ← new Node(arr[i]); queue.enqueue(p.side)
      i ← i + 1
  return root

Python

def build(arr):
    if not arr:
        return None
    root = Node(arr[0])
    queue, i = deque([root]), 1
    while i < len(arr):
        p = queue.popleft()
        for side in ('left', 'right'):
            if i < len(arr) and arr[i] is not None:
                child = Node(arr[i])
                setattr(p, side, child)
                queue.append(child)
            i += 1
    return root

JavaScript

function build(arr) {
  if (arr.length === 0) return null;
  const root = { val: arr[0], left: null, right: null };
  const queue = [root];
  let i = 1;
  while (i < arr.length) {
    const p = queue.shift();
    for (const side of ['left', 'right']) {
      if (i < arr.length && arr[i] !== null) {
        p[side] = { val: arr[i], left: null, right: null };
        queue.push(p[side]);
      }
      i++;
    }
  }
  return root;
}

Practice problems (6)

Build from a level-order array Warm-up

The array [8, 3, 10, 1, 6, null, 14] lists a binary tree level by level, left to right; null marks a missing child. The tree below has the right shape, but its values were placed depth-first. Put each value where the level-order array says it goes.

Children of index i Warm-up

A complete tree of 11 nodes is stored in an array, root at index 0. Find the children and the parent of index 4 using only arithmetic.

Which tree is complete? Standard

A complete tree has every level full except maybe the last, and the last level is filled from the left with no gaps. Pick the complete tree.

Count the nodes Standard

Given the root of a binary tree, return the number of nodes in it. Each node has val, left and right; a missing child is null.

Sum of all values Standard

Given the root of a binary tree, return the sum of all node values. An empty tree has sum 0.

Check completeness Challenge

Given the root of a binary tree, return true if it is complete: every level is full except maybe the last, and the last level is filled from the left with no gaps. Such a tree fits in an array with no empty slots.

Related topics

Next on the path: Pre-order, in-order, post-order