Sub topic 14
Binary Heaps: Complete Trees, Heap Property, and Array Indices
Assume you know arrays, zero-based indexing, Big-O notation, and basic tree terms such as root, parent, child, and leaf.
A binary heap is a complete binary tree that follows a heap property. A complete binary tree fills every level from left to right. The last level may be incomplete, but it has no gaps.
A min-heap has a value at least as large as its parent. Therefore, the smallest value is at the root. A max-heap has a value no larger than its parent, so the largest value is at the root.
The heap property compares each node with its children. It does not require the left subtree to contain smaller values than the right subtree. This differs from a binary search tree.
Array representation
Because a complete tree has no missing positions before its last node, it can be stored compactly in an array. With zero-based indexing, a node at index i has these positions:
| Relationship | Index formula |
|---|---|
| Parent of `i` | `(i - 1) // 2` |
| Left child of `i` | `2 * i + 1` |
| Right child of `i` | `2 * i + 2` |
| Last internal node | `n // 2 - 1` |
A parent exists only when i > 0. A child exists only when its index is less than the heap size n. All indices from n // 2 through n - 1 are leaves.
Consider the min-heap [4, 7, 6, 12, 9, 10, 8]. Index 0 contains 4, whose children are at indices 1 and 2, containing 7 and 6. Index 2 contains 6, whose children are at indices 5 and 6, containing 10 and 8.
Checking the heap property
For a min-heap, check every internal node:
a[i] <= a[2*i + 1]when the left child exists.a[i] <= a[2*i + 2]when the right child exists.
A single violation means the array is not a min-heap. For example, [4, 7, 3] is not a min-heap because 3 is a child of 4 but is smaller than its parent.
The tree remains a heap if equal parent and child values occur. The property is non-strict: parent values may be equal to child values.
The complete-tree rule determines the shape. The heap property determines the ordering. Both rules must hold.
Exercise
For the zero-based array [2, 5, 3, 9, 7, 8], identify the parent of index 4 and decide whether the array is a min-heap.
Show answer
The parent of index 4 is index (4 - 1) // 2 = 1, which contains 5. Every parent is no larger than its children, so the array is a min-heap.