7Heaps and Balanced Trees
What is a heap?
In the priority queue lessons you saw that every structure was slow either at insertion or at removal. A heap does both in O(log n). It manages this with two simple rules: the tree always stays complete, and every node is smaller than its children. This lesson covers what a heap is, what it is not and where it is used.
1Two rules
A heap is a binary tree. For a binary tree to count as a heap, two rules must hold together:
- Shape rule: the tree is complete. Every level except the last is full, and the last level fills from left to right.
- Order rule: every node is smaller than or equal to its children. This is called the heap property.
The second rule holds between every parent and child, so it chains: the root is smaller than its children, they are smaller than theirs, and so on. As a result the smallest value is always at the root. The tree below is a heap.
2Min-heap and max-heap
The order rule can point either way. A heap where every node is smaller than or equal to its children is a min-heap; one where every node is larger than or equal to its children is a max-heap. A min-heap has the smallest value at its root, a max-heap the largest. Both are written with the same code; only the direction of the comparison changes.
The heap lessons on this site use a min-heap; as in the priority queue lessons, the smaller value comes out first. We will need a max-heap in the heap sort lesson. In an exam, check which one is being asked for.
3Two trees that are not heaps
The order rule is checked only between a parent and its children. In the tree below 12 is smaller than its parent 20. Even though the root is still the smallest value, the tree is not a heap.
The shape rule matters just as much. In the tree below the order rule holds everywhere, but the last level has a gap after 40 and the nodes on the right come after that gap. The tree is not complete, so it is not a heap.
4Why is a heap fast?
In a complete tree each level holds twice as many nodes as the one above: 1, 2, 4, 8. So a complete tree with n nodes has a height equal to the whole part of log₂ n. With 1000 nodes the height is 9; with a million it is 19. Every heap operation moves along a single path, from the root to a leaf or from a leaf to the root, so it takes at most as many steps as the height.
| Operation | Time | How |
|---|---|---|
| Look at the minimum (peek) | O(1) | Read the root |
| Insert | O(log n) | Put it at the end, move it up: sift up |
| Remove the minimum | O(log n) | Move the last one to the root, move it down: sift down |
| Build a heap from n values | O(n) | Heapify |
| Search for a value | O(n) | The order rule does not help a search |
A complete tree brings one more advantage: it fits in an array with no gaps. The index formulas from binary tree in an array work for a heap too, and no pointers are needed. That is why a heap is almost always coded with an array.
5Heap versus binary search tree
Both are binary trees and both have an order rule, but the rules differ. In a binary search tree the left subtree is smaller and the right subtree is larger; that speeds up searching for a value, and an inorder traversal returns the values sorted. In a heap there is an order only between parent and child, not between left and right.
| Heap | Binary search tree | |
|---|---|---|
| Order rule | Parent ≤ children | Left < node < right |
| Shape | Always complete | Depends on insertion order |
| Smallest value | At the root, O(1) | The leftmost node |
| Search for a value | O(n) | O(log n) if balanced |
| Inorder traversal | Not sorted | Sorted |
| Usually coded with | An array | Linked nodes |
6Where are heaps used?
- Priority queues: as you saw in the priority queue comparison, a heap makes both insertion and removal fast. Java's
java.util.PriorityQueueand Python'sheapqare binary heaps. - Sorting: heap sort sorts an array in O(n log n) with no extra memory.
- The k largest items: to keep the 10 largest values of a huge stream of data, a min-heap of 10 elements is enough.
- Graph algorithms: shortest paths (Dijkstra) and minimum spanning trees (Prim) take the next closest vertex from a heap.
- Operating systems and timers: a heap finds the job whose time runs out first.
The word "heap" also appears in memory management: the region where C's malloc hands out memory is called the heap too. There is no link between the two; the same word is used for two different things.
7What this part covers
- Heap with an array: indexes and the heap property, insertion, removing the minimum, building a heap and heap sort.
- Heap with linked nodes: the parent pointer and the last place, the same operations in the same order, and a comparison of the two.
- Balanced trees: AVL trees, red-black trees and B-trees.
8Try it
Is the tree holding 5, 9, 7, 12, 10, 6 in level order a min-heap?
The answer is C. 6 sits at position 5; its parent is at (5-1)/2 = 2, which holds 7, and since 7 > 6 the rule is broken. 10 is at position 4; its parent at (4-1)/2 = 1 holds 9, and 9 < 10, so there is no problem there.
Show the answer
The answer is C. 6 sits at position 5; its parent is at (5-1)/2 = 2, which holds 7, and since 7 > 6 the rule is broken. 10 is at position 4; its parent at (4-1)/2 = 1 holds 9, and 9 < 10, so there is no problem there.
What is the height of a heap with 10 nodes (height counted in edges)?
The answer is A. A complete tree fills its levels as 1, 2, 4: the first three levels hold 7 nodes, and the remaining 3 go into the fourth level. Four levels mean 3 edges between the root and the deepest leaf.
Show the answer
The answer is A. A complete tree fills its levels as 1, 2, 4: the first three levels hold 7 nodes, and the remaining 3 go into the fourth level. Four levels mean 3 edges between the root and the deepest leaf.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.