01 / 20

Tracing
Recursion

Learn to trace recursive method calls, understand call stack behavior, and predict the output of recursive Java programs.

Java

What Is Recursion?

A recursive method is a method that calls itself. Each call works on a smaller version of the original problem until it reaches a base case: a condition where it stops calling itself and returns a value directly.

Base Case
The stopping condition. Without it, the method calls itself forever (stack overflow).
Recursive Case
The method calls itself with a modified argument, moving closer to the base case.

The Call Stack

Every time a method is called, Java creates a stack frame and pushes it onto the call stack. The frame stores the method's local variables and its return address. When the method returns, its frame is popped off the stack.

main() factorial(3) factorial(2) factorial(1) ← top push pop CALL STACK (LIFO)

Anatomy of a Recursive Method

public static int factorial(int n) { if (n == 1) { // base case return 1; } return n * factorial(n - 1); // recursive case }
1
Base case: when \( n = 1 \), return 1 directly. No more calls.
2
Recursive case: return \( n \times \texttt{factorial}(n - 1) \). The argument shrinks by 1 each time.
3
Progress toward base: each call reduces \( n \), guaranteeing the base case is eventually reached.

Two Phases: Winding and Unwinding

Every recursion has two phases. During winding, the method pushes new calls onto the stack. During unwinding, each call returns its result to the caller.

WINDING (calls) factorial(4) factorial(3) factorial(2) factorial(1) → base! UNWINDING (returns) returns 1
\(2 \times 1 \rightarrow 2\)
\(3 \times 2 \rightarrow 6\)
\(4 \times 6 \rightarrow 24\)
factorial(4) = 24
\(4 \times 3 \times 2 \times 1\)

Recursion vs Iteration

Recursion Iteration
Mechanism Method calls itself Loop repeats a block
Memory Uses call stack frames Uses loop variables
Termination Base case Loop condition false
Risk StackOverflowError Infinite loop
Best for Tree/graph traversal, divide-and-conquer Simple counting, linear scans

How to Trace Recursion

1
Identify the base case. What input makes the method return immediately without calling itself?
2
Write down each call. Start from the initial call and write each recursive call on a new line, noting the argument value.
3
Hit the base case. When you reach the base condition, write the returned value.
4
Unwind the stack. Substitute each returned value back into the previous call's expression and evaluate.
5
Read the final result from the first call. If the method prints, note the order: prints may happen during winding, unwinding, or both.

Example 1: Recursive Sum

public static int sum(int n) { if (n == 0) return 0; return n + sum(n - 1); }

Trace sum(4):

WINDING sum(4)
\(= 4 + \text{sum}(3)\)
sum(3)
\(= 3 + \text{sum}(2)\)
sum(2)
\(= 2 + \text{sum}(1)\)
sum(1)
\(= 1 + \text{sum}(0)\)
sum(0) → returns 0 UNWINDING sum(0) = 0
\(\text{sum}(1) = 1 + 0 = 1\)
\(\text{sum}(2) = 2 + 1 = 3\)
\(\text{sum}(3) = 3 + 3 = 6\)
\(\text{sum}(4) = 4 + 6 = 10\)
Answer: 10

Example 2: Print Order Matters

public static void mystery(int n) { if (n <= 0) return; System.out.print(n + " "); // prints BEFORE recursive call mystery(n - 1); }
public static void mystery2(int n) { if (n <= 0) return; mystery2(n - 1); System.out.print(n + " "); // prints AFTER recursive call }

Example 3: String Recursion

public static String reverse(String s) { if (s.length() <= 1) return s; return reverse(s.substring(1)) + s.charAt(0); }

Trace reverse("cat"):

WINDING reverse("cat") = reverse("at") + 'c' reverse("at") = reverse("t") + 'a' reverse("t") → "t" base case: length = 1 UNWINDING "t" "t" + 'a' = "ta" "ta" + 'c' = "tac" Result: "tac"

Example 4: Fibonacci (Two Recursive Calls)

public static int fib(int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); }

Trace fib(4): each call spawns two sub-calls, creating a tree.

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 9 total calls for a single value of 4

Call Stack Snapshot

Here is the call stack at the deepest point of factorial(4), just before the base case returns:

CALL STACK (top → bottom)
factorial(1) → n = 1 ← executing
factorial(2) → waiting for factorial(1)
factorial(3) → waiting for factorial(2)
factorial(4) → waiting for factorial(3)
main()

Stack Unwinding in Action

Once the base case returns, frames pop one at a time, each substituting the returned value:

RETURNING VALUES
factorial(1) → returns 1
factorial(2) → 2 * 1 = returns 2
factorial(3) → 3 * 2 = returns 6
factorial(4) → 4 * 6 = returns 24
main() → receives 24

Common Mistakes

✕ Missing Base Case
Forgetting the base case leads to infinite recursion and a StackOverflowError. Always check the stopping condition first.
✕ No Progress Toward Base
If the argument doesn't change (e.g., calling f(n) instead of f(n-1)), the base case is never reached.
✕ Confusing Print Order
Print before the recursive call: values appear top-down (winding). Print after: values appear bottom-up (unwinding).

Recursion Cheat Sheet

Concept What to Look For Key Rule
Base case if/return with no recursive call Must be reachable
Recursive case Method calls itself Argument must shrink
Winding phase Calls stacking up Print before call: top-down
Unwinding phase Returns flowing back Print after call: bottom-up
Stack depth Count of active frames Too deep = StackOverflow
Tree recursion Two+ recursive calls (fib) Exponential call count

Question 1 of 5

What is the value of mystery(3)?

Question 2 of 5

What does printStuff(4) output?

Question 3 of 5

How many total calls to recur() are made when evaluating recur(5)? (Include the initial call.)

Question 4 of 5

A recursive method has no base case. What happens when it is called?

Question 5 of 5

What does build(4) return?