What's happening?
- Every call that is not the base case waits for a smaller call — and each waiting call is a frame on the call stack.
- The base case answers without calling anything, and that is what stops the recursion.
- Then the frames come off the stack newest first, each finishing its own work with the answer from below.
Complexity
- Time
- O(n) calls for factorial(n)
- Space
- O(n) stack frames
Where you'll meet it
Tree and graph traversal, file-system walks, parsers, divide-and-conquer algorithms like merge sort, and backtracking.
Common mistake
A missing or unreachable base case: the stack keeps growing until the program crashes with a stack overflow.
FAQ
What is a base case?
The input small enough to answer directly, without another call. Every recursion needs one.
Why does deep recursion cause a stack overflow?
Each waiting call keeps a frame on the call stack; too many frames exhaust the memory set aside for it.
Is recursion slower than a loop?
Often slightly, because of the extra frames — but for trees and graphs it is usually far clearer.