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:
- Structural property: The tree is complete — every level except possibly the bottom is full, and the bottom level is filled from left to right.
- Ordering property: Parent children (max-heap) or Parent children (min-heap).
Array Representation
The complete binary tree structure enables a compact array representation. Using 1-indexed arrays:
- Root at .
- Left child of node : .
- Right child of node : .
- Parent of node : .
The root has no parent (). A child is absent when or 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 nodes has height . The number of nodes at level is at most , and the deepest leaf is at level .
- For : .
- For : (a perfect binary tree).
Operations that traverse from root to leaf (or leaf to root) are bounded by the height, giving time.
Heap vs Binary Search Tree
| Property | Heap | BST |
|---|---|---|
| Left-right ordering | None; only parent-child inequality | Left subtree < root < right subtree |
| Structure | Complete tree | No structural guarantee (can be degenerate) |
| Finding min/max | — always at root | — traverse to leftmost/rightmost |
| Searching | — must scan | if balanced |
| In-order traversal | Not meaningful | Produces sorted order |
| Use case | Priority queue, Heapsort | Dictionary, 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 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 rather than the cost of full sorting.
Summary
| Property | Detail |
|---|---|
| Structure | Complete binary tree, array representation |
| Parent at | |
| Left child at | |
| Right child at | |
| Height | |
| Heap property (max) | |
| Heap vs BST | Heap: weak order, strong structure; BST: strong order, weak structure |