Lesson 6 · Foundations

Recursion and the Call Stack

A recursive function solves a problem by calling itself on a smaller piece of it, until the piece is small enough to answer directly. The call stack keeps each paused call's values until the smaller answer comes back.

Recursion and the Call Stack concept diagramA visual explanation of the layout and operations shown in this lesson.fact(4)4 × fact(3)fact(3)3 × fact(2)fact(2)2 × fact(1)fact(1)base case = 1unwind: 1 → 2 × 1 → 3 × 2 → 4 × 6 = 24
1

Base Case and Recursive Case

Recursion is when a function solves a problem by calling itself on a smaller version of the same problem. It works because each call shrinks the input until it reaches a case simple enough to answer outright.

Every correct recursive function has two parts. The base case answers directly, with no further calls: an empty list, a leaf node, n ≤ 1. The recursive case makes the problem smaller, calls the function on it, and uses the result.

Factorial is the usual first example: 4! = 4 × 3!, and 3! = 3 × 2!, down to 1! = 1. The code below is exactly that, and the walk-through further down shows each call being paused and resumed.

Three things must hold, and a missing one is where recursion goes wrong. There must be a base case; every call must move toward it; and the base case must be reachable from every valid input. f(n - 2) with the base case n == 0 never stops for odd n: 5, 3, 1, −1, −3 and on until the stack runs out. factorial(-1) fails the same way if the base case tests n == 0 instead of n <= 1.

  • Base case: answer directly, no call
  • Recursive case: shrink, call, then combine
  • Check that every input, including odd, zero and negative ones, reaches the base case
  • Recursive data (trees, nested lists) is where recursion reads most naturally
2

What the Call Stack Holds

The call stack is the region of memory where a program keeps one stack frame per active call. A frame holds the call's parameters, its local variables and the address to return to. It is pushed when the call starts and popped when it returns, which is why each level keeps its own copy of n.

So recursion is not free in memory. A chain d calls deep holds d frames at once, so the space is O(d) even when the function allocates nothing. The same work in a loop uses O(1).

The stack is a fixed-size region, commonly 8 MB for a Linux main thread and 1 MB on Windows. Going past it is a stack overflow and the program dies. Python stops earlier on purpose: its default limit is 1000 frames, and it raises RecursionError instead of crashing.

What costs memory is depth, not the number of calls. Naive Fibonacci makes an exponential number of calls, but the left branch finishes before the right one starts, so only n frames exist at any moment: O(2ⁿ) time, O(n) space. For a tree, the depth is its height: about 20 levels for a balanced tree of a million nodes, but a million levels for the same nodes in a chain, which overflows.

  • One frame per active call: parameters, locals, return address
  • Space is O(depth), even when the function allocates nothing
  • Python's default limit is 1000 frames; C and Java overflow at a size set by the stack
  • A recursive tree walk that passes on balanced tests can fail on a long chain
3

Trusting the Smaller Call

  1. What is the smallest input I can answer at once? That is the base case
  2. How do I make the input smaller? That is the recursive call
  3. Given the smaller answer, how do I build mine? That is the combining step

Tracing every call by hand works for factorial and falls apart on a tree. It is also unnecessary. Instead, assume the recursive call already returns the right answer for the smaller input, and write only the step that uses it.

To find a tree's height: assume the calls return the correct heights of the two subtrees; then the answer is 1 + the larger of them. How the subtrees worked out their heights does not matter.

This is proof by induction, not hope. Check the base case is right. Check that if the smaller calls are right, the combining step is right. Together they cover every input, and that is the argument an exam answer should give.

Where the combining work sits also sets the order of visits in a tree. Work before the calls gives pre-order, between them in-order, after them post-order, so the three tree traversals are one recursion with the work moved.

  • Write the base case first, then the combining step
  • Never trace more than one level when writing; trace only to debug
  • Work placed before, between or after the calls gives pre-, in- and post-order
Key reference

Terms, operations, and practical uses

Core vocabulary

  • Recursive callA function calling itself on a smaller input.
  • Base caseThe input answered directly, which stops the calls.
  • Call stackMemory holding one frame per active call; frames come off in last-in, first-out order.

Performance

  • Stack overflowThe crash when the frames outgrow the stack region; Python raises RecursionError at 1000 frames by default.
  • Tail recursionThe call is the last action, so a compiler that supports it can reuse the frame.
  • MemoizationStoring each subproblem's answer so repeated calls return at once.

Practical uses

  • Tree traversalEach subtree is a smaller tree, so one call per child fits the shape.
  • Divide and conquerSplit the input, solve the parts recursively, combine, as merge sort does.
  • BacktrackingTry a choice, recurse, and undo it when it leads nowhere.
Implementation

Code in Python, C++ and Java

def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)
print(factorial(4))
#include <iostream>
using namespace std;

int factorial(int n) {
    if (n <= 1) return 1;
    return n * factorial(n - 1);
}

int main() {
    cout << factorial(4) << '\n';
}
public class Main {
    static int factorial(int n) {
        if (n <= 1) return 1;
        return n * factorial(n - 1);
    }

    public static void main(String[] args) {
        System.out.println(factorial(4));
    }
}
Watch it run

Step through it

Running on factorial(4)

factorial(4)bottom of the call stackfactorial(4)n = 4 · waiting: 4 × factorial(3)frames on the stack: 1each frame keeps its own n
Step 1

Call factorial(4)

One frame is pushed, holding n = 4. The base case asks whether n <= 1; it is not, so this call needs factorial(3) before it can multiply. The frame pauses with 4 × ? still to work out.

Output
1 / 12
4

Types of Recursion

The types of recursion are named by how the calls are arranged. Direct recursion calls itself; indirect (mutual) recursion goes through another function that calls back, like isEven(n) calling isOdd(n - 1), or a parser where parseExpression calls parseTerm, which calls parseExpression again for a bracketed part.

Linear recursion makes one call per invocation, so the calls form a chain n deep. Tree recursion makes two or more, so the calls branch: naive Fibonacci makes 9 calls for fib(4) and 177 for fib(10). That is why it is exponential while factorial is linear, though the two look alike.

Tail recursion is when the recursive call is the very last thing the function does, with nothing left to multiply or add afterwards. fact(n, acc) returning fact(n - 1, n × acc) is tail recursive; n × fact(n - 1) is not, because the multiply still waits. A compiler can then reuse the current frame instead of pushing a new one (tail call optimisation), so the space drops to O(1).

Support is uneven. Scheme guarantees it. C and C++ compilers usually do it with optimisation turned on, but the language does not promise it. Java and Python never do; CPython's creator declined it because it erases the stack traces used for debugging. JavaScript's ES2015 standard requires it, but only Safari implements it. In those languages a deep tail-recursive function still needs rewriting as a loop.

  • Direct or indirect: does the function call itself, or go through another?
  • Linear or tree: one call per level, or several?
  • Head or tail: is there work left after the call returns?
  • Nested recursion passes a recursive call as the argument, as in Ackermann's function
5

Recursion vs Iteration

Recursion against iteration is not about power: any recursion can be rewritten with a loop and an explicit stack, and any loop can be written as recursion. The choice is about which version is clearer and which one survives the input sizes you expect.

Choose a loop for plain repetition and for chains that could be deep, such as walking a long linked list. Choose recursion when the data is itself recursive: tree traversals, divide and conquer, backtracking. There a loop would just rebuild the call stack by hand.

When the same subproblem appears in several branches, plain recursion repeats the work; caching each result turns exponential time into linear. That is memoization, and the recursive shape stays the same. To work out how long a recursive function takes, write its running time as a recurrence relation.

Good practice problems: Fibonacci Number for memoization, Pow(x, n) for halving the input, Reverse Linked List for recursion over a list, Subsets for tree recursion, and the Tower of Hanoi, which needs 2ⁿ − 1 moves.

The same task written both ways
RecursionIteration
Extra memoryO(depth) stack framesO(1), or an explicit stack you manage
Failure at large sizeStack overflow or RecursionErrorNone from depth
SpeedA call and return per stepUsually a little faster
Fits bestTrees, graphs, nested data, divide and conquer, backtrackingSimple counting loops and long linear chains
  • Every recursion has a loop-plus-stack version, and the reverse
  • Deep linear chains: prefer a loop
  • Branching or nested structure: prefer recursion
  • Same subproblem twice: add a cache