Smaller parts and priorities: recursion, trees and heaps
After this: Spot answers built from smaller parts, tree levels, and the k largest, and say why a min-heap keeps the largest.
On this page · 5 sections · 3 checks
The last lesson's problems were all about a row read from left to right. Some problems have a different shape. The answer is built from smaller copies of the same problem, or the data sits in levels, or you only need the few best items out of many. This lesson works three rows of the cue table for those shapes.
Built from smaller parts: recursion
The cue is "the answer for the whole is built from answers for smaller parts". A function that solves a problem by calling itself on a smaller part is using . The sum of a list is its first item plus the sum of the rest:
- sum of
[3, 1, 4]= 3 + sum of[1, 4] - sum of
[1, 4]= 1 + sum of[4] - sum of
[4]= 4 + sum of[] - sum of
[]= 0, because nothing is left to add.
Four calls are open at the deepest point, one for each list above. Then the answers come back: 4, then 5, then 8. The Recursion on lists and strings lesson shows these frames one at a time.
def sum_list(items): if not items: # nothing left to add return 0 return items[0] + sum_list(items[1:]) # the first item, plus the sum of the rest
print(sum_list([3, 1, 4]))8
import java.util.*;
public class Main { static int sumList(List<Integer> items) { if (items.isEmpty()) return 0; // nothing left to add return items.get(0) + sumList(items.subList(1, items.size())); // the first item, plus the sum of the rest }
public static void main(String[] args) { System.out.println(sumList(List.of(3, 1, 4))); }}8
Levels and depth: a tree traversal
The cues are "levels", "depth" and "every node of a tree". They mean you must go through the whole tree, which is a . Counting levels is recursion again: an empty tree has 0 levels, and a node adds one level to the deeper of its two sides. The bottom nodes 1, 6 and 14 each have 1 level, 3 and 10 each have 2, and the top node 8 has 3.
class TreeNode: def __init__(self, value, left=None, right=None): self.value = value self.left = left # another TreeNode, or None self.right = right
def levels(node): if node is None: # no tree: no levels return 0 return 1 + max(levels(node.left), levels(node.right))
root = TreeNode(8, TreeNode(3, TreeNode(1), TreeNode(6)), TreeNode(10, None, TreeNode(14)))print(levels(root))3
class TreeNode { int value; TreeNode left, right; // another TreeNode, or null
TreeNode(int value) { this.value = value; }
TreeNode(int value, TreeNode left, TreeNode right) { this.value = value; this.left = left; this.right = right; }}
public class Main { static int levels(TreeNode node) { if (node == null) return 0; // no tree: no levels return 1 + Math.max(levels(node.left), levels(node.right)); }
public static void main(String[] args) { TreeNode root = new TreeNode(8, new TreeNode(3, new TreeNode(1), new TreeNode(6)), new TreeNode(10, null, new TreeNode(14))); System.out.println(levels(root)); }}3
The tree node class is called TreeNode here, not Node as in the binary-trees tutorial, because the interview tutorials also use a Node for linked lists. The cost is O(n): each node is visited once.
The few best: a heap of size k
The cues are "k largest", "k smallest", "top k" and "next most urgent". They point to a . Keep a min-heap of at most k values. Push each value; whenever the heap holds more than k, pop once.
- Push 5:
[5]. Push 1:[1, 5]. - Push 9: three values. Pop the smallest, 1:
[5, 9]. - Push 3, then pop the smallest, which is 3 itself:
[5, 9]. - Push 7, then pop 5:
[7, 9]. The answer, largest first, is[9, 7].
Why a min-heap to find the largest? The heap holds the best k so far. When a new value pushes it over k, one value must leave, and the one to throw out is the smallest of them. A min-heap keeps exactly that value on top. Step through the same pushes and pops below.
- Push 5Push 5. The heap holds one value, fewer than 2, so nothing comes out.
- Push 1
- Push 9
- Pop the minimum
- Push 3
- Pop the minimum
- Push 7
- Pop the minimum
- 0
empty
Push a few values and watch them sift up.
The function pushes every value, and pops whenever the heap holds more than k. At the end it sorts the k kept values, largest first. Each push and pop works on a heap of at most k + 1 values, so it costs about log k steps; for n values the total is O(n log k). When k is a small fixed number, such as 2 or 3, that is a fixed number of steps per value, so the total grows like O(n). Sorting the whole list instead costs O(n log n), and needs every value at once.
| Cue | Tool | Time |
|---|---|---|
| "built from answers for smaller parts" | recursion | depends on the problem; n calls for the sum |
| "levels", "depth", "every node" | tree traversal | O(n) |
| "k largest", "k smallest", "top k" | heap of size k | O(n log k) |
Check yourself
A problem says: “Given the prices of 10,000 flights, return the 3 cheapest.” Which tool do its words point to?
The 2 largest of [5, 1, 9, 3, 7], with a min-heap of size 2. After pushing 5, 1 and 9, the heap holds three values, so it pops once. What does the heap array hold after that pop?
You want the k largest values of a long list, keeping only k values at a time. Which heap do you keep, and why?
Honesty notes
- Spot a problem whose answer is built from the same problem on a smaller part, and solve it with recursion.
- Read “levels” and “depth” as a tree traversal, and count levels as one more than the deeper side.
- Keep the k largest values in a min-heap of size k, popping whenever it holds more than k, and say why the smallest kept value is the one to throw out.
- Say that a heap of size k costs O(n log k), which is O(n) when k is a small fixed number.