CIE AS & A Level Computer Science, section 19.2 (Recursion)
Benefits
- The code is often shorter and easier to read, matching the definition of the problem.
- Natural for problems that are defined in terms of themselves, such as tree and graph traversal.
- Suits divide and conquer (the problem is split into smaller versions of itself).
Drawbacks
- Each call uses memory for its stack frame, so deep recursion can cause a stack overflow.
- It can be slower, because of the overhead of many calls.
- Some recursion repeats work: the simple Fibonacci function calculates the same value many times.
calls = 0
def fib(n):
global calls
calls += 1
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)
fib(20)
print(calls) # 21891 calls for one answer
An iterative version does the work in about 20 steps:
def fib_iter(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
print(fib_iter(20)) # 6765
Choosing
| Use recursion for | Use iteration for |
|---|---|
| tree structures and traversals | simple counting or running totals |
| divide and conquer (binary search, merge sort) | very deep repetition |
| problems with a natural recursive definition | where speed and memory matter |
Example where recursion is neat
Printing every item in a folder and its sub-folders, or in-order traversal of a binary tree, is simple with recursion, but awkward with a loop, which needs its own stack.
Common mistake: saying recursion is "always better" or "always worse". It is a trade-off: clear code against memory use. Also, a problem solved by recursion can always be solved by iteration (perhaps with a stack).
Exam tip: give one benefit and one drawback, and link your choice to the problem. For example, "a tree traversal is easier to write recursively because the structure is itself recursive".
Check yourself
Give one benefit of recursion.
The code is shorter and clearer for problems that are naturally defined in terms of themselves, such as trees.
Give one drawback of recursion.
Each call uses stack memory, so deep recursion can cause a stack overflow, and it may be slower than a loop.
Why is the simple recursive Fibonacci function inefficient?
It recalculates the same values many times.