3.4.10 · D3Trees

Worked examples — Heap — max-heap and min-heap properties

2,400 words11 min readBack to topic

Before anything else, one reminder of the machinery you will use in every example — burned into a picture so we never call an index without a picture behind it.

Figure — Heap — max-heap and min-heap properties
Recall The three index formulas (0-based)

left(i) ::: 2i+1 right(i) ::: 2i+2 parent(i) ::: floor((i-1)/2)


The scenario matrix

Every heap problem is one of these cells. The worked examples that follow are each tagged with the cell they cover, so by the end you have hit all of them.

Cell Situation What makes it tricky
A Validate a correct heap Must check siblings are NOT compared
B Validate a broken heap Spot the one bad parent–child pair
C Node with only a left child (odd n) right(i) ≥ n → must skip, not crash
D Sift-down from the root (max-heapify) Choose the larger child each step
E Insert that doesn't move (sift-up ends immediately) Parent already dominates
F Insert that bubbles to the root (full path) Longest possible sift-up
G Degenerate inputs: n=0, n=1, all-equal Empty/single-node/ties are all valid heaps
H Word problem (real-world priority queue) Translate a story into heap ops
I Exam twist: "is this array sorted ⇒ is it a heap?" and vice-versa The sorted↔heap confusion

Forecast for yourself as you read: which cell do you find hardest? Most people miss C (the missing right child) and I (sorted vs heap). Watch those two.


Worked examples


Recall

Recall One line per cell

Cell C guard you must never forget? ::: child < n before accessing A[2i+1] or A[2i+2]. When does a node have only a left child? ::: When ; happens for exactly one node iff is even. Sift-down: swap with which child in a max-heap? ::: The larger child, so the new parent dominates the sibling too. Is an empty array a valid heap? ::: Yes — vacuously (no parent–child pair to break). Can one array be both a valid max- and min-heap? ::: Yes, if all elements are equal. Sorted ascending ⇒ valid min-heap? ::: Yes, always. Heap ⇒ sorted? ::: No.


Connections

  • Priority Queue — Example 9 is a priority queue in disguise.
  • Heapsort — repeated extract-max on Example 5's result.
  • Build-Heap (Heapify) O(n) — many sift-downs like Example 5, bottom-up.
  • Complete Binary Tree — the shape rule behind "append at the last leaf."
  • Binary Search Tree — Example 10's contrast: a BST would let you search.
  • Big-O Notation — every example's swap count ≤ height = .

Case Map

check only

remove or fix

insert

guard

ends early

full path

edge

story

trap

Heap operation

Validate cells A B C

Sift down cell D

Sift up cells E F

child less than n

No swap cell E

Reaches root cell F

Degenerate cell G

Priority queue cell H

Sorted vs heap cell I