A heap is a tree, but it has no node objects. The tree is the list, read by index.
The children of index i sit at 2i + 1 and 2i + 2
Predict
In the list [7, 12, 18, 30, 21, 45, 60], index i has its children at 2i + 1 and 2i + 2. What are the children of 12, at index 1?
Here's the heapified list h = [7, 12, 18, 30, 21, 45, 60], drawn as a tree. The number under each node is its index in the list.
h = [7, 12, 18, 30, 21, 45, 60], as a tree
Each node's index is under it. The parent of index i is (i - 1) // 2.
Read the tree level by level, left to right, and you get the list: 7, then 12 and 18, then 30, 21, 45 and 60. That fixes the index arithmetic:
The root is index 0.
The children of index i sit at 2 * i + 1 and 2 * i + 2.
The parent of index i sits at (i - 1) // 2.
Check one: index 1 holds 12, and its children at 3 and 4 hold 30 and 21.
Every parent is no bigger than its children. That's the only rule, and it's called the heap invariant. The heapq docs define a heap that way. Siblings and cousins can be in any order, which is why 30 can sit before 21.
Each level fills before the next one starts, so the tree is as short as it can be. 7 items take 3 levels, and a million take 20. A push or a pop walks one path between the root and a leaf, one item per level. So it touches about log2n items at most, where log2n is the number of times you can halve n before you reach 1. That's where the O(log n) comes from.
In the editor, write is_heap(h): check the heap invariant on a plain list, with the parent of index i at (i - 1) // 2.
Pick an answer above to see the rest
Instructions
1
Write is_heap(h): True when no item is smaller than its parent at (i - 1) // 2, and False otherwise.