Base and recursive cases
Some problems contain smaller copies of themselves: to count what is in a box of boxes, you count each inner box the same way. A recursive routine calls itself on each smaller part. Its base case knows the answer at once; its general case calls itself and adds up the answers.
Tavren’s lantern store: boxes inside boxes
Tavren lantern hire stores its lanterns in nested compartments numbered 0 to 4. The task: count every lantern in a compartment and in all the compartments inside it. Start by finding its base case and its general case.
| Compartment | Lanterns stored directly | Children |
|---|---|---|
| 0 | 31 | 1, 2 |
| 1 | none | 3, 4 |
| 2 | 27, 8 | none |
| 3 | 14 | none |
| 4 | 22, 19 | none |
- 1“Local” counts only the lanterns stored directly in a compartment.
- 2General case: total = local count + the totals of all its children.
- 3Base case: a compartment with no children. Its local count is already the answer.
Why the calls always stop
A routine that calls itself could keep going for ever. This one always stops, because:
- The compartments form a finite tree: no compartment contains one of its own ancestors.
- Every recursive call moves down to a child, so fewer levels remain below it.
- Every branch therefore reaches a leaf, which is the base case.
- A base case is not enough by itself: the general case must move towards it. A link back to an ancestor would call forever.
1 Which compartments are base cases?
2 Compartment 1 holds no lanterns directly. Why is its total not 0?
3 What two things must every recursive routine have?
- 12, 3, 4: they have no children
- 2its total includes its children: 0 + 1 + 2 = 3
- 3a base case that returns without another call, and a general case that calls itself on a smaller problem
Tracing recursive calls
Recursion can look like magic until you watch it run. The secret is that the caller waits: it stops partway through, lets the call do its job, and carries on only when that call returns a value. To follow it, track two things: each call entered and each call returned.
The task and the function
count_lanterns(0) on Tavren’s lantern store.own = [1, 0, 2, 1, 2]: the lanterns stored directly in compartments 0 to 4.children = [[1, 2], [3, 4], [], [], []]: compartment 0 contains 1 and 2; compartment 1 contains 3 and 4.1def count_lanterns(place): 2subtotal = own[place] 3if children[place] == []: 4return subtotal 5for child in children[place]: 6subtotal = subtotal + count_lanterns(child) 7return subtotal
Draw the calls as a tree
It helps to see the whole shape before the detail. Each box is one call: the black numbers give the order calls are entered, the blue labels what each one returns.
Trace every call and return, in order
The tree shows which calls happen, but not when. The trace puts them in time order, with each subtotal as it changes: one row for each time a call is entered, resumes or returns. Depth is how many callers are waiting.
| Place | Depth | Subtotal | Returns | What happens | |
|---|---|---|---|---|---|
| enter | 0 | 0 | 1 | starts with its own 1; calls child 1 and waits | |
| starts with its own 1; calls child 1 and waits | |||||
| enter | 1 | 1 | 0 | starts with its own 0; calls child 3 and waits | |
| starts with its own 0; calls child 3 and waits | |||||
| enter | 3 | 2 | 1 | no children: the base case | |
| no children: the base case | |||||
| return | 3 | 2 | 1 | its frame is finished; 1 goes back to place 1 | |
| its frame is finished; 1 goes back to place 1 | |||||
| resume | 1 | 1 | 1 | child 3 returned 1: 0 + 1 = 1 | |
| child 3 returned 1: 0 + 1 = 1 | |||||
| enter | 4 | 2 | 2 | no children: the base case | |
| no children: the base case | |||||
| return | 4 | 2 | 2 | its frame is finished; 2 goes back to place 1 | |
| its frame is finished; 2 goes back to place 1 | |||||
| resume | 1 | 1 | 3 | child 4 returned 2: 1 + 2 = 3 | |
| child 4 returned 2: 1 + 2 = 3 | |||||
| return | 1 | 1 | 3 | its frame is finished; 3 goes back to place 0 | |
| its frame is finished; 3 goes back to place 0 | |||||
| resume | 0 | 0 | 4 | child 1 returned 3: 1 + 3 = 4 | |
| child 1 returned 3: 1 + 3 = 4 | |||||
| enter | 2 | 1 | 2 | no children: the base case | |
| no children: the base case | |||||
| return | 2 | 1 | 2 | its frame is finished; 2 goes back to place 0 | |
| its frame is finished; 2 goes back to place 0 | |||||
| resume | 0 | 0 | 6 | child 2 returned 2: 4 + 2 = 6 | |
| child 2 returned 2: 4 + 2 = 6 | |||||
| return | 0 | 0 | 6 | its frame is finished; 6 goes back to the main program | |
| its frame is finished; 6 goes back to the main program | |||||
| Event and place | Subtotal | Continuation |
|---|---|---|
| Enter 0 | 1 | Call child 1 |
| Enter 1 | 0 | Call child 3 |
| Enter 3 | 1 | Leaf: return 1 |
| Return 3 | 1 | Place 1 adds 1: subtotal 1 |
| Enter 4 | 2 | Leaf: return 2 |
| Return 4 | 2 | Place 1 adds 2: subtotal 3 |
| Return 1 | 3 | Place 0 adds 3: subtotal 4 |
| Enter 2 | 2 | Leaf: return 2 |
| Return 2 | 2 | Place 0 adds 2: subtotal 6 |
| Return 0 | 6 | Main program receives 6 |
- 1Each call keeps its own local subtotal. Entering a child never resets the caller’s value.
- 2A caller resumes at line 6, using the value it had before the call.
- 3Entry order: 0, 1, 3, 4, 2. Return order: 3, 4, 1, 2, 0. The last return goes to the main program.
1 Another store has own = [2, 1, 0, 3] and children = [[1, 2], [3], [], []]. In what order are the calls entered?
2 In what order do they return?
3 What does count_lanterns(0) return for this store?
- 10, 1, 3, 2
- 23, 1, 2, 0
- 36: place 1 returns 4 (its own 1 + 3), place 2 returns 0, so 2 + 4 + 0 = 6
The runtime call stack
A caller that is waiting must not forget where it was: its own subtotal, and the line to come back to. The computer keeps this in a stack frame on the runtime stack: the parameters, the local values and the return location. The newest call always finishes first, so frames come off last in, first out.
The call is still count_lanterns(0) with own = [1, 0, 2, 1, 2]: compartment 0 contains 1 and 2; compartment 1 contains 3 and 4. Line 4 returns a leaf’s subtotal; line 6 adds a returned value to the caller’s subtotal.
One frame for every waiting call
The stack at its deepest, while leaf 3 is running. Be able to draw it for any moment of the run: one frame per waiting call, newest on top.
- 1Leaf 3 returns 1. Its frame is removed. Place 1 resumes at line 6: 0 + 1 = 1.
- 2Leaf 4 returns 2. Place 1 resumes again: 1 + 2 = 3, and returns 3.
- 3Place 0 resumes with the 1 it kept: 1 + 3 = 4. It still has child 2 to call.
What happens as the calls return
Then the stack unwinds. Each finished call hands its answer back, and its frame disappears:
- A frame stays on the stack until its call returns. Place 0’s frame stays until its total reaches 6.
- The return location is the instruction after the call, not the start of the routine.
- The result is passed to the caller before the finished frame is discarded.
- There is one compiled copy of the routine. Each call gets its own frame, not its own copy of the code.
1 Name three things a stack frame holds.
2 Which frames are on the stack while count_lanterns(3) is running? Give them from bottom to top.
3 A routine calls itself with no base case. What happens to the stack?
- 1parameters, local variables (local state) and the return location
- 2place 0, place 1, place 3
- 3frames are pushed until the stack has no space left: stack overflow
Writing and testing a recursive function
Writing recursion is easier than reading it. Start from the shape of the data: a compartment has its own lanterns and some compartments inside it. The function only has to say that, and count each lantern exactly once.
The complete program
The whole program: the data, the function you traced, and three calls to try it.
own = [1, 0, 2, 1, 2] children = [[1, 2], [3, 4], [], [], []] def count_lanterns(place): subtotal = own[place] if children[place] == []: return subtotal for child in children[place]: subtotal = subtotal + count_lanterns(child) return subtotal print(count_lanterns(0)) print(count_lanterns(1)) print(count_lanterns(2))
Output: 6, then 3, then 2, each on its own line.
How to write one: three moves
Look at how the function was built. The same three moves work for any recursive task:
- 1Base result first: what is returned when there is nothing smaller to call? (A leaf returns its own count.)
- 2A strictly smaller argument: each call is on a child, never on the same compartment.
- 3Use the returned value: add it to the subtotal. A call whose result is ignored adds nothing.
Test both cases
A recursive function can be right for a leaf and still go wrong higher up. Test each case, and say what each test proves.
| Input | Expected | What it tests |
|---|---|---|
| 3 | 1 | The base case: a leaf makes no calls. |
| 1 | 3 | Combining: 0 local + child totals 1 + 2. |
| 0 | 6 | Two levels: 1 local + subtree 3 + subtree 2. |
- Check the answer another way: the contents are 31; 27, 8; 14; 22, 19, which is six lanterns.
- Testing only a leaf would not show whether child results are combined correctly.
1 What does the function return for a compartment with no children?
2 Line 6 is changed to count_lanterns(child) with no addition. What does count_lanterns(0) return, and why?
3 Give one test input that checks the general case.
- 1its own local count
- 21: the children’s results are thrown away, so only compartment 0’s own count is returned
- 31 or 0: any compartment that has children
Recursive tree traversal
Recursion is at its best on trees. The compartments were one kind of tree; in a binary tree each node has at most two children, left and right. A traversal visits every node once. Inorder goes left subtree, node, right subtree, and on a binary search tree it prints the values smallest first.
The tree and the code
Tavren also keeps its lantern IDs in a binary search tree, held in a table. Each row gives the index of the left child, the lantern ID and the index of the right child; −1 means no child. The root is row 0. Task: output the IDs in ascending order.
| Index | Left | ID | Right |
|---|---|---|---|
| 0 | 1 | 31 | -1 |
| 1 | 3 | 14 | 2 |
| 2 | 4 | 27 | -1 |
| 3 | -1 | 8 | -1 |
| 4 | 5 | 22 | -1 |
| 5 | -1 | 19 | -1 |
def inorder(current): if current == NULL: return if tree[current][0] != NULL: inorder(tree[current][0]) print(tree[current][1]) if tree[current][2] != NULL: inorder(tree[current][2]) inorder(root)
Trace the traversal, step by step
inorder waits for its calls just as the lantern count did. The difference is that it prints a value between its two calls, so the output depends on where each call picks up again:
Output: 8, 14, 19, 22, 27, 31, each on its own line. The links and the array order never change.
inorder handles the node between its calls.1 Give the three traversal orders by where the node is processed.
2 Give the preorder output for Tavren’s tree.
3 Give the postorder output for Tavren’s tree.
- 1preorder: node first; inorder: node in the middle; postorder: node last
- 231, 14, 8, 27, 22, 19
- 38, 19, 22, 27, 14, 31
Recursion or a loop?
Recursion is not the only way: iteration, a loop, can do the same job. The loop has to keep its own list of the work still to do, which the stack did for free. So when is each the better choice?
The same task with a loop
own = [1, 0, 2, 1, 2] and children = [[1, 2], [3, 4], [], [], []], as before.pending = [0] total = 0 while pending: place = pending.pop() total = total + own[place] for child in children[place]: pending.append(child) print(total)
Compare recursion and the loop
Both programs print 6. What differs is where the waiting work is kept, and what that costs.
| Property | Recursive count | Iterative count |
|---|---|---|
| Pending work | Runtime stack frames | Explicit pending list |
| Local totals | One subtotal per active call | One running total |
| Time | O(n): visit each compartment | O(n): visit each compartment |
| Extra storage | O(h) active frames | O(n) worst-case pending nodes |
- n is the number of compartments; h is the height of the tree.
- This recursion has at most three active frames: 0, 1, 3 (or 0, 1, 4).
- A very deep chain needs a frame per level and can exhaust the runtime stack.
- Every call also costs a little time to push and pop its frame.
Which to choose: it depends on the data
- Tree or nested data: recursion mirrors the structure and is easier to read.
- A simple repeated scan: a loop is clearer and needs no extra frames.
- Recursion does not prevent repeated work: solving the same sub-problem on several branches wastes time.
- The iterative program takes child 2 before child 1 (last in, first out). The total is still 6. If the order matters, push the children in reverse or use a queue.
1 Where does each method keep the work that is still waiting?
2 Give one reason to choose recursion and one reason to choose iteration.
3 A tree is a single chain 5 000 compartments deep. What risk does the recursive version run?
- 1recursion: stack frames on the runtime stack; iteration: its own pending list
- 2recursion is clearer for nested data such as trees; iteration uses less memory for a simple repeated scan and has no call overhead
- 3a frame for every level: the runtime stack can run out of space (stack overflow)