Skip to content

9618 · Unit 23 · Papers 3–4: Theory and practical programming

Recursion and call stacks.

9618 · Unit 23 · Recursion and call stacks
Revisionbyexamplicity

Base and recursive cases

§19.2 · Recursion

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.

01 local10 local22 local31 local42 local
CompartmentLanterns stored directlyChildren
0311, 2
1none3, 4
227, 8none
314none
422, 19none
  1. 1
    “Local” counts only the lanterns stored directly in a compartment.
  2. 2
    General case: total = local count + the totals of all its children.
  3. 3
    Base 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.
Your turn

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?

  1. 1
    2, 3, 4: they have no children
  2. 2
    its total includes its children: 0 + 1 + 2 = 3
  3. 3
    a base case that returns without another call, and a general case that calls itself on a smaller problem
Tick what you can do now
Practise with s25/31 Q4(b) (older paper: recursion features)
1 / 6
9618 · Unit 23 · Recursion and call stacks
Revisionbyexamplicity

Tracing recursive calls

§19.2 · Recursion

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

Task: trace 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.
Python · count one subtree
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.

place 0own 11returns 6place 1own 02returns 3place 2own 25returns 2place 3own 13returns 1place 4own 24returns 2

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.

PlaceDepthSubtotalReturnsWhat happens
enter001starts with its own 1; calls child 1 and waits
starts with its own 1; calls child 1 and waits
enter110starts with its own 0; calls child 3 and waits
starts with its own 0; calls child 3 and waits
enter321no children: the base case
no children: the base case
return321its frame is finished; 1 goes back to place 1
its frame is finished; 1 goes back to place 1
resume111child 3 returned 1: 0 + 1 = 1
child 3 returned 1: 0 + 1 = 1
enter422no children: the base case
no children: the base case
return422its frame is finished; 2 goes back to place 1
its frame is finished; 2 goes back to place 1
resume113child 4 returned 2: 1 + 2 = 3
child 4 returned 2: 1 + 2 = 3
return113its frame is finished; 3 goes back to place 0
its frame is finished; 3 goes back to place 0
resume004child 1 returned 3: 1 + 3 = 4
child 1 returned 3: 1 + 3 = 4
enter212no children: the base case
no children: the base case
return212its frame is finished; 2 goes back to place 0
its frame is finished; 2 goes back to place 0
resume006child 2 returned 2: 4 + 2 = 6
child 2 returned 2: 4 + 2 = 6
return006its frame is finished; 6 goes back to the main program
its frame is finished; 6 goes back to the main program
Event and placeSubtotalContinuation
Enter 01Call child 1
Enter 10Call child 3
Enter 31Leaf: return 1
Return 31Place 1 adds 1: subtotal 1
Enter 42Leaf: return 2
Return 42Place 1 adds 2: subtotal 3
Return 13Place 0 adds 3: subtotal 4
Enter 22Leaf: return 2
Return 22Place 0 adds 2: subtotal 6
Return 06Main program receives 6
  1. 1
    Each call keeps its own local subtotal. Entering a child never resets the caller’s value.
  2. 2
    A caller resumes at line 6, using the value it had before the call.
  3. 3
    Entry order: 0, 1, 3, 4, 2. Return order: 3, 4, 1, 2, 0. The last return goes to the main program.
Your turn

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?

  1. 1
    0, 1, 3, 2
  2. 2
    3, 1, 2, 0
  3. 3
    6: place 1 returns 4 (its own 1 + 3), place 2 returns 0, so 2 + 4 + 0 = 6
Tick what you can do now
Practise with w25/43 Q3(a)(i) (older paper: recursive counting)
2 / 6
9618 · Unit 23 · Recursion and call stacks
Revisionbyexamplicity

The runtime call stack

§19.2 · Recursion

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.

Review the saved stack and the resumed caller.Recorded snapshot: leaf 3 activeplace 0 · subtotal 1resume line 6place 1 · subtotal 0resume line 6place 3 · subtotal 1return line 4place → value3 → 14 → 21 → 3Now: place 0 · subtotal 4Next: call child 2.
  1. 1
    Leaf 3 returns 1. Its frame is removed. Place 1 resumes at line 6: 0 + 1 = 1.
  2. 2
    Leaf 4 returns 2. Place 1 resumes again: 1 + 2 = 3, and returns 3.
  3. 3
    Place 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.
Your turn

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?

  1. 1
    parameters, local variables (local state) and the return location
  2. 2
    place 0, place 1, place 3
  3. 3
    frames are pushed until the stack has no space left: stack overflow
Tick what you can do now
Practise with w25/32 Q12(b) (older paper: stack and recursion)
3 / 6
9618 · Unit 23 · Recursion and call stacks
Revisionbyexamplicity

Writing and testing a recursive function

§19.2 · Recursion

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.

Python · complete program: data, function, calls
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:

  1. 1
    Base result first: what is returned when there is nothing smaller to call? (A leaf returns its own count.)
  2. 2
    A strictly smaller argument: each call is on a child, never on the same compartment.
  3. 3
    Use 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.

InputExpectedWhat it tests
31The base case: a leaf makes no calls.
13Combining: 0 local + child totals 1 + 2.
06Two 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.
Your turn

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.

  1. 1
    its own local count
  2. 2
    1: the children’s results are thrown away, so only compartment 0’s own count is returned
  3. 3
    1 or 0: any compartment that has children
Tick what you can do now
Practise with w25/43 Q3(a)(i) (older paper: write a recursive counting function)
4 / 6
9618 · Unit 23 · Recursion and call stacks
Revisionbyexamplicity

Recursive tree traversal

§19.2 · Recursion

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.

IndexLeftIDRight
0131-1
13142
2427-1
3-18-1
4522-1
5-119-1
leftleftrightleftleft31614281275224193Blue: the order inorder outputs the IDs
Python · root = 0, NULL = −1; Tavren’s tree
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:

1
Follow left: cell 0 (31) → cell 1 (14) → cell 3 (8). Both child links at 8 are null: skip them, output 8, then return.
2
Resume cell 1: output 14, then traverse its right subtree at cell 2 (27).
3
Cell 2’s left subtree outputs 19, 22. Resume cell 2 and output 27; finally resume cell 0 and output 31.

Output: 8, 14, 19, 22, 27, 31, each on its own line. The links and the array order never change.

Preorder: node, left, right. Postorder: left, right, node. Moving the node operation changes the traversal; it does not change the links. inorder handles the node between its calls.
Your turn

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.

  1. 1
    preorder: node first; inorder: node in the middle; postorder: node last
  2. 2
    31, 14, 8, 27, 22, 19
  3. 3
    8, 19, 22, 27, 14, 31
Tick what you can do now
Practise with s26/43 Q3(e)(i), (e)(ii), (e)(iii)
5 / 6
9618 · Unit 23 · Recursion and call stacks
Revisionbyexamplicity

Recursion or a loop?

§19.2 · Recursion

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

Task: count the lanterns in Tavren’s store without recursion.
own = [1, 0, 2, 1, 2] and children = [[1, 2], [3, 4], [], [], []], as before.
The program prints 6, the same total as the recursive function.
Python · iterative count of the same lantern store
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.

PropertyRecursive countIterative count
Pending workRuntime stack framesExplicit pending list
Local totalsOne subtotal per active callOne running total
TimeO(n): visit each compartmentO(n): visit each compartment
Extra storageO(h) active framesO(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.
Your turn

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?

  1. 1
    recursion: stack frames on the runtime stack; iteration: its own pending list
  2. 2
    recursion is clearer for nested data such as trees; iteration uses less memory for a simple repeated scan and has no call overhead
  3. 3
    a frame for every level: the runtime stack can run out of space (stack overflow)
Tick what you can do now
Practise with w25/32 Q12(b) (older paper: stack mechanism)
6 / 6