01 / 20

Tracing
Recursion

Learn to trace recursive function calls, visualize the call stack, and understand how Python resolves each frame to produce a final result.

Python

What Is Recursion?

A function is recursive when it calls itself as part of its own execution. Every recursive function has two essential components: a base case that stops the recursion and a recursive case that moves toward it.

def factorial(n): if n == 0: # base case return 1 return n * factorial(n - 1) # recursive case

The Call Stack Explained

Python uses a call stack (a last-in, first-out data structure) to keep track of function calls. When a function is called, a new frame is pushed onto the stack. When it returns, the frame is popped off.

factorial(0) return 1 factorial(1) return 1 * factorial(0) factorial(2) return 2 * factorial(1) factorial(3) return 3 * factorial(2) ← TOP (newest) ← BOTTOM (oldest) PUSH ORDER Call stack for factorial(3)

Why Tracing Matters

Tracing means manually walking through each call and return to predict the output. It builds a mental model of how Python actually executes your code, which is essential for debugging and designing recursive solutions.

Predict Output
Know exactly what a recursive function returns without running it.
Debug Errors
Identify missing base cases or incorrect recursive steps instantly.
Ace Exams
AP CS A and technical interviews test tracing constantly.

The Two Rules of Recursion

1
Base case: A condition that returns a value without making another recursive call. This is what stops the recursion.
2
Recursive case: The function calls itself with a smaller or simpler argument, moving closer to the base case with every call.

Anatomy of a Recursive Call

def countdown(n): if n == 0: return "Done" print(n) return countdown(n - 1) Base Case Recursive Case Execution: countdown(3) countdown(3) prints 3 countdown(2) prints 2 countdown(1) prints 1 countdown(0) returns "Done" Output: 3, 2, 1

Iteration vs Recursion

Iteration (loop) Recursion
Mechanism Repeats via for / while Repeats via self-call
State Updated in variables Passed as arguments
Termination Loop condition becomes False Base case is reached
Memory \( O(1) \) (constant) \( O(n) \) (stack frames)
Best for Simple repetition Trees, divide & conquer

How to Trace: Step by Step

1
Write the initial call and its argument values.
2
Check the base case. If met, write the return value and stop this branch.
3
Expand the recursive call. Substitute arguments and repeat from step 2.
4
Unwind the stack. Replace each waiting call with its returned value, bottom to top.
5
Compute the final result from the outermost frame.

Example: Tracing factorial(4)

def factorial(n): if n == 0: return 1 return n * factorial(n - 1)
WINDING (pushing frames) factorial(4) = 4 * factorial(3) factorial(3) = 3 * factorial(2) factorial(2) = 2 * factorial(1) factorial(1) = 1 * factorial(0) factorial(0) = 1 (base case) UNWINDING (popping frames) factorial(0) → 1 factorial(1) → 1 * 1 = 1 factorial(2) → 2 * 1 = 2 factorial(3) → 3 * 2 = 6 factorial(4) → 4 * 6 = 24 Result: 24

Example: Tracing sum_list

def sum_list(lst): if lst == []: return 0 return lst[0] + sum_list(lst[1:])

Example: Fibonacci Tree

def fib(n): if n <= 1: return n return fib(n - 1) + fib(n - 2)
fib(4) fib(3) fib(2) fib(2) fib(1) → 1 fib(1) → 1 fib(0) → 0 fib(1)→1 fib(0)→0 fib(4) = 3

Winding vs Unwinding

Winding Phase
Calls stack up. Each call pauses, waiting for the inner call to return. Frames are pushed onto the stack.
Unwinding Phase
The base case returns. Each paused call resumes, using the returned value. Frames are popped off the stack.

Head vs Tail Recursion

Head Recursion Tail Recursion
Work done After the recursive call returns Before the recursive call
Return expression n * factorial(n - 1) factorial(n - 1, acc * n)
Stack usage Must keep all frames Could reuse one frame
Python optimized? No No (Python has no TCO)

Tracing with an Accumulator

def factorial_acc(n, acc=1): if n == 0: return acc return factorial_acc(n - 1, acc * n)

Notice: with an accumulator, the result is built up during winding. The unwinding phase just passes the final value back unchanged through every frame.

Common Mistakes

✕ Missing Base Case
Forgetting the stopping condition causes infinite recursion and a RecursionError.
✕ Not Shrinking Input
Calling the function with the same or larger argument never reaches the base case.
✕ Ignoring Return Values
Writing factorial(n - 1) without return discards the result. The function returns None.

Recursion Cheat Sheet

Concept Key Idea
Base Case Returns a value without recursing
Recursive Case Calls itself with a smaller input
Call Stack LIFO structure storing each frame
Winding Calls are pushed, waiting to resolve
Unwinding Return values propagate back up
Time Complexity Depends on branching: linear or exponential
Stack Overflow RecursionError when limit (~1000) exceeded

Question 1 of 5

What does mystery(7) return?

Question 2 of 5

In a recursive function, what happens if there is no base case?

Question 3 of 5

How many total stack frames are created when calling power(2, 5) (including the initial call)?

Question 4 of 5

What is the output of concat(4)?

Question 5 of 5

Which of the following best describes unwinding the call stack?