Sub topic 2
The heap property and the complete tree shape
This chapter assumes you can read Python lists and tuples, use zero-based indexing, and talk about binary trees (parent, child, depth). It also assumes you know what O(log n) means. The previous chapter introduced the priority queue as an interface. Here you will see the two rules that let a heap implement it efficiently.
Two rules, two jobs
A binary heap is a binary tree that obeys two rules at once.
- Heap property. In a min-heap, every node is less than or equal to each of its children. In a max-heap, every node is greater than or equal to each of its children.
- Complete tree shape. Every level is full except possibly the last. The last level is filled from left to right with no gaps.
The heap property decides where the most urgent item lives. The shape decides how tall the tree can be. Each rule supports a different operation, and you need both.
What the heap property gives you
Follow any path from the root downward and the values never decrease. So the root is the smallest value in the whole tree, and peek is a single lookup, O(1).
The property is weaker than sorted order. It compares a node only to its own children, never to its siblings or cousins. In the tree above, 4 is above 9 and 5, but 3 sits next to 4 and is smaller than both of 4's children. The levels are not sorted either: 8 and 7 sit on the same level as 9 and 5.
This weakness is deliberate. Keeping everything sorted costs more on every insert. Keeping only the parent-child ordering is cheap to repair after a change, and that is all a priority queue needs.
What the complete shape gives you
A tree that is filled level by level has a predictable height. A complete binary tree with n nodes has height floor(log2 n). With 7 nodes the height is 2. With 1,000,000 nodes it is only 19.
Insertion and removal both repair the tree by walking along one root-to-leaf path. The shape keeps that path short, so the repair costs O(log n) steps. Without the shape rule, inserting sorted data could build a long chain with height n, and operations would degrade to O(n).
The shape rule has a second benefit. Because there are no gaps, the nodes can be packed into a plain array with no pointers. The next chapter shows how.
Checking both rules in code
This function checks a tree stored as a list, using the same level-by-level order the shape rule describes. The position of each item decides its parent, which the next chapter explains fully. For now, note that the children of the item at index i sit at 2*i + 1 and 2*i + 2.
def is_min_heap(a):
n = len(a)
for i in range(n):
for child in (2 * i + 1, 2 * i + 2):
if child < n and a[i] > a[child]:
return False
return True
print(is_min_heap([2, 4, 3, 9, 5, 8, 7])) # True
print(is_min_heap([2, 4, 3, 1, 5, 8, 7])) # False: 4 > its child 1
print(is_min_heap([5, 1, 8, 3])) # False: 5 > its child 1A list has no gaps, so the shape rule is satisfied automatically. Only the heap property needs to be checked.
Common mistakes
- Assuming that the second smallest value is always the root's left child. It is one of the root's two children, but you cannot tell which without comparing them.
- Treating "complete" as "full". A full tree has every level filled. A complete tree may have a partly filled last level, as long as it fills from the left.
- Expecting
a[1] <= a[2]. Siblings have no required order.
Exercise
Is the list [1, 3, 2, 7, 4, 5] a valid min-heap? Name the rule you used to decide, and say which indexes you compared.
Show answer
Yes. Check each parent against its children using children at 2i + 1 and 2i + 2. Index 0 (value 1) has children 3 and 2, both larger. Index 1 (value 3) has children 7 and 4, both larger. Index 2 (value 2) has only a left child at index 5 (value 5), which is larger. Indexes 3 to 5 have no children. The heap property holds, and a list has no gaps, so the shape rule holds too.