Sub topic 13
Tracing Recursive Algorithms
This chapter assumes you can already trace procedure calls with a call stack, build trace tables, and read the 1-based pseudocode conventions used throughout this tutorial. A recursive algorithm is one that solves a problem by calling itself on a smaller version of the same problem. You trace it with the same tools as any other procedure call. The difficulty is bookkeeping: many frames of the same function are open at once, each with its own copy of the parameters, and each frame waits for the calls below it to finish.
The Two Parts of Every Recursive Function
Every correct recursive function has two parts:
- Base case: an input small enough to answer directly, without another call.
- Recursive case: the step that calls the function on a smaller input and combines that result with some local work.
When you trace, check three things before computing any values:
- A base case exists.
- Every recursive call moves the input closer to a base case.
- Every input your algorithm accepts eventually reaches a base case, not only the inputs you happen to try.
The third check finds the most recursion bugs. We return to it below.
Winding and Unwinding
A recursive trace has two phases. During the winding phase, calls push new frames onto the stack and no frame finishes yet. Each frame stops partway through its own line and waits for the call below it. During the unwinding phase, the base case returns. Each waiting frame then resumes, finishes its pending work, and returns to the frame above it.
Here is factorial again, with the indented trace style:
FUNCTION Fact(n)
IF n ≤ 1 THEN
RETURN 1
END IF
RETURN n × Fact(n - 1)
END FUNCTION
Trace of Fact(3):
Fact(3) calls Fact(2)
Fact(2) calls Fact(1)
Fact(1) returns 1
Fact(2) returns 2 × 1 = 2
Fact(3) returns 3 × 2 = 6Indentation shows stack depth. A line with more indentation belongs to a frame pushed later. Notice that the multiplication n × ... happens only on the way back up. While winding, every frame holds a pending operation, work it cannot do until its call returns.
A Recursion Trace Table
For anything bigger than factorial, an indented trace gets hard to read. A trace table built for recursion has one row per frame and records the pending work explicitly:
| depth | call | base case? | pending work | returns |
|---|---|---|---|---|
| 0 | Fact(3) | no | 3 × [Fact(2)] | 6 |
| 1 | Fact(2) | no | 2 × [Fact(1)] | 2 |
| 2 | Fact(1) | yes | none | 1 |
Fill the table in two passes. Go downward to fill the first four columns, which is the winding phase. Then go upward to fill the returns column, which is unwinding. Each returns value is the pending work with the bracketed call replaced by the value from the row below.
Recursion over an Array
Recursion over arrays usually shrinks an index instead of a number. This function returns A[1] + A[2] + ... + A[k]:
FUNCTION SumTo(A, k)
IF k = 0 THEN
RETURN 0
END IF
RETURN SumTo(A, k - 1) + A[k]
END FUNCTIONTrace SumTo(A, 3) with A = [4, 1, 5]:
| depth | k | base case? | pending work | returns |
|---|---|---|---|---|
| 0 | 3 | no | [SumTo(A, 2)] + A[3] = [ ] + 5 | 10 |
| 1 | 2 | no | [SumTo(A, 1)] + A[2] = [ ] + 1 | 5 |
| 2 | 1 | no | [SumTo(A, 0)] + A[1] = [ ] + 4 | 4 |
| 3 | 0 | yes | none | 0 |
All frames share the same array A. Only k differs between frames. Writing A once, outside the table, saves space and makes it obvious that the array is never copied or changed. If the function modified A, you would need a separate column for the array's state, because every frame would see those changes.
Tree Recursion: More Than One Call per Frame
When a function makes two or more recursive calls, the calls form a tree instead of a chain. Fibonacci is the standard example:
FUNCTION Fib(n)
IF n ≤ 1 THEN
RETURN n
END IF
RETURN Fib(n - 1) + Fib(n - 2)
END FUNCTIONThe order matters. Fib(n - 1) runs to completion, including all of its own calls, before Fib(n - 2) starts. A linear trace therefore follows the tree depth-first, left to right.
The matching indented trace, in execution order:
Fib(4) calls Fib(3)
Fib(3) calls Fib(2)
Fib(2) calls Fib(1)
Fib(1) returns 1
Fib(2) calls Fib(0)
Fib(0) returns 0
Fib(2) returns 1 + 0 = 1
Fib(3) calls Fib(1)
Fib(1) returns 1
Fib(3) returns 1 + 1 = 2
Fib(4) calls Fib(2)
Fib(2) calls Fib(1)
Fib(1) returns 1
Fib(2) calls Fib(0)
Fib(0) returns 0
Fib(2) returns 1 + 0 = 1
Fib(4) returns 2 + 1 = 3Two facts come out of this trace. First, the stack is never deeper than four frames, even though nine calls happen. Stack depth follows the longest path in the tree, while total work follows the number of nodes. Second, Fib(2) is computed twice. Repeated subproblems like this are why plain tree recursion can be very slow. Tracing by hand shows you the waste before you measure it.
Common Errors a Trace Exposes
| Error | Symptom in the trace | Typical fix |
|---|---|---|
| Missing base case | Depth grows with no row marked "base case" | Add a direct answer for the smallest input |
| Base case skipped over | Parameter jumps past the base value | Use ≤ or ≥ instead of = |
| Input does not shrink | Same parameter value appears in two consecutive rows | Change the argument, e.g. n - 1 instead of n |
| Return value discarded | A frame calls itself but returns nothing or a constant | RETURN the combined result |
| Wrong combining step | Base case is right but the values going up are wrong | Recheck the pending work at the lowest non-base row |
Desk-Checking a Skipped Base Case
This function is meant to return n + (n - 2) + (n - 4) + ..., stopping at zero:
FUNCTION SumByTwos(n)
IF n = 0 THEN
RETURN 0
END IF
RETURN n + SumByTwos(n - 2)
END FUNCTIONA trace with n = 4 looks fine: 4 + 2 + 0 = 6. Now trace an odd input, n = 3:
SumByTwos(3) calls SumByTwos(1)
SumByTwos(1) calls SumByTwos(-1)
SumByTwos(-1) calls SumByTwos(-3)
... n never equals 0The parameter steps over the base case, so the recursion never stops. A real program would crash with a stack overflow. Change the test to IF n ≤ 0 THEN. Then SumByTwos(3) returns 3 + 1 + 0 = 4. The lesson is the third check from the start of this chapter: pick at least one trace input from each class of values, such as odd and even, or zero and negative, that could reach the base case by a different route.
Factorial has a related, milder edge case. Fact(-2) hits n ≤ 1 at once and returns 1, so it terminates but gives a meaningless answer. Decide whether that is acceptable, or whether the function should reject negative input.
Checking a Trace by Running It
Once your hand trace is done, you can confirm it by adding indentation to the output of a real program. This Python version prints the same trace shown earlier for Fact(3):
def fact(n, depth=0):
pad = " " * depth
if n <= 1:
print(f"{pad}Fact({n}) returns 1")
return 1
print(f"{pad}Fact({n}) calls Fact({n - 1})")
result = n * fact(n - 1, depth + 1)
print(f"{pad}Fact({n}) returns {n} × {result // n} = {result}")
return result
fact(3)Output:
Fact(3) calls Fact(2)
Fact(2) calls Fact(1)
Fact(1) returns 1
Fact(2) returns 2 × 1 = 2
Fact(3) returns 3 × 2 = 6The extra depth parameter is only for display. Each frame gets its own copy, exactly as each frame gets its own n.
Trusting the Recursion
Tracing every call works for small inputs, but a trace of Fib(20) is not practical. Once you have traced the base case and one or two levels above it by hand, switch to a shorter argument. Assume the recursive call returns the correct answer for the smaller input, then check that the current frame combines that answer correctly. For SumTo, if SumTo(A, k - 1) really is A[1] + ... + A[k - 1], then adding A[k] gives the correct sum for k. This reasoning has the same structure as a proof by induction. It is only valid after your trace confirms the base case and confirms that every input reaches it.
Exercises
Exercise
Build a recursion trace table for SumTo(A, 2) with A = [7, 3, 9]. What does it return, and how many frames are on the stack at the deepest point?
Show answer
Rows: depth 0, k = 2, pending [SumTo(A, 1)] + 3, returns 10; depth 1, k = 1, pending [SumTo(A, 0)] + 7, returns 7; depth 2, k = 0, base case, returns 0. It returns 10, and three frames are on the stack at the deepest point. A[3] = 9 is never read.
Exercise
How many calls does Fib(5) make in total, counting the original call? Find the answer without drawing the whole tree.
Show answer
Let C(n) be the number of calls. C(0) = C(1) = 1, and C(n) = C(n - 1) + C(n - 2) + 1. So C(2) = 3, C(3) = 5, C(4) = 9 (this matches the diagram), and C(5) = 9 + 5 + 1 = 15.
Exercise
This function should return the number of digits in a non-negative integer n: IF n < 10 THEN RETURN 1 END IF; RETURN 1 + Digits(n DIV 10). Trace Digits(0), Digits(9), and Digits(1050). Is there an input that fails?
Show answer
Digits(0) returns 1, which is correct. Digits(9) returns 1. Digits(1050) calls Digits(105), Digits(10), and Digits(1); Digits(1) returns 1, then the values going back up are 2, 3, 4. It returns 4, which is correct. No non-negative input fails, because n DIV 10 strictly decreases until n < 10. A negative input, however, also satisfies n < 10 and returns 1, so the caller must guarantee n ≥ 0.
Exercise
A student writes Count(n): IF n = 0 THEN RETURN 0 END IF; Count(n - 1); RETURN n. They expect Count(3) to return 3 + 2 + 1 + 0 = 6. Trace it, explain the result, and fix it.
Show answer
Count(3) calls Count(2), which calls Count(1), which calls Count(0), which returns 0. Each frame ignores the returned value and returns its own n, so Count(1) returns 1, Count(2) returns 2, and Count(3) returns 3. The return value is discarded. Fix: RETURN n + Count(n - 1).