Skip to content
Part IA Lent Term

The Binary Heap Structure

Definition

A (binary) max-heap is a complete binary tree satisfying the heap property: the value at every node is greater than or equal to the values of its children. A min-heap reverses this: every node is less than or equal to its children.

Two defining properties:

  1. Structural property: The tree is complete — every level except possibly the bottom is full, and the bottom level is filled from left to right.
  2. Ordering property: Parent \ge children (max-heap) or Parent \le children (min-heap).

A max-heap showing parent values greater than or equal to children, and the corresponding array layout

Array Representation

The complete binary tree structure enables a compact array representation. Using 1-indexed arrays:

  • Root at A[1]A[1].
  • Left child of node ii: A[2i]A[2i].
  • Right child of node ii: A[2i+1]A[2i + 1].
  • Parent of node ii: A[i/2]A[\lfloor i/2 \rfloor].

The root has no parent (1/2=0\lfloor 1/2 \rfloor = 0). A child is absent when 2i2i or 2i+12i + 1 exceeds A.heap_size (which may be less than A.length since the heap may occupy only a prefix of the array).

Height of a Heap

A heap with nn nodes has height h=log2nh = \lfloor \log_2 n \rfloor. The number of nodes at level kk is at most 2k2^k, and the deepest leaf is at level hh.

  • For n=6n=6: h=log26=2.58=2h = \lfloor \log_2 6 \rfloor = \lfloor 2.58 \rfloor = 2.
  • For n=15n=15: h=log215=3h = \lfloor \log_2 15 \rfloor = 3 (a perfect binary tree).

Operations that traverse from root to leaf (or leaf to root) are bounded by the height, giving O(logn)O(\log n) time.

Heap vs Binary Search Tree

PropertyHeapBST
Left-right orderingNone; only parent-child inequalityLeft subtree < root < right subtree
StructureComplete treeNo structural guarantee (can be degenerate)
Finding min/maxO(1)O(1) — always at rootO(h)O(h) — traverse to leftmost/rightmost
SearchingO(n)O(n) — must scanO(h)O(h) if balanced
In-order traversalNot meaningfulProduces sorted order
Use casePriority queue, HeapsortDictionary, ordered map

The heap is a semi-structure: cheaper to maintain than a fully ordered structure, yet sufficient for repeatedly extracting the largest (or smallest) element.

Semi-Structured Nature

In a max-heap of nn elements:

  • The largest is at exactly one place: the root.
  • The second largest is in one of two places: the root’s children.
  • The third largest is in one of three places: the other root child, or either child of the second largest.

This “partial-sort” property is what makes heap operations O(logn)O(\log n) rather than the O(nlogn)O(n \log n) cost of full sorting.

Summary

PropertyDetail
StructureComplete binary tree, array representation
Parent at iii/2\lfloor i/2 \rfloor
Left child at ii2i2i
Right child at ii2i+12i + 1
Heightlog2n\lfloor \log_2 n \rfloor
Heap property (max)A[i]A[2i],A[2i+1]A[i] \ge A[2i], A[2i+1]
Heap vs BSTHeap: weak order, strong structure; BST: strong order, weak structure