Watch calls build up, reach the base case, then return in reverse order.
Select Play or Next line to follow Python execution.
Python implementation
The highlight marks the next line to execute. Values show the state before that line.
1def recursive_sum(n):2 if n == 0:3 return 04 subtotal = recursive_sum(n - 1)5 return n + subtotal
B2.4.5: a simple non-branching recursive function. Each call makes at most one recursive call. For non-negative n: O(n) time and O(n) auxiliary call-stack space. A loop can use O(1) auxiliary space.
By the end of this lesson
Identify a base case and explain progress towards it.
Construct and trace a simple non-branching recursive function.
Explain recursion in quicksort, tree traversal and fractal drawing.
Account for memory used by active recursive calls.
Work through the lesson
01 · 10 minutes
Predict the result
Use the recursive-sum animation. Predict recursive_sum(4), then step through the Python one line at a time. Explain why recursive_sum(0) stops.
02 · 15 minutes
Follow the call stack
Record n for each active call. Pause at the base case, then predict the values returned as the calls finish.
03 · 15 minutes
Construct and test
Write a simple non-branching recursive function. Test its base case and a small input. Explain how each call gets closer to stopping.
04 · 10 minutes
Explore applications
Use the quicksort, tree traversal and fractal animations to explain smaller subproblems. These branching examples illustrate applications; their full implementation is not required by B2.4.5.
05 · 5 minutes
Compare memory
Compare the recursive sum with a loop. Explain why pending recursive calls require extra memory.
Before you leave
Exit question
What must be true of both the base case and each recursive call for the function to stop?