Sub topic 2
Recursion on Recursive Data: Lists and Trees
This chapter assumes you can write Python functions and loops, and that you can read Big-O notation. It also assumes you know what a base case and a call stack are.
Structural Recursion
Some data structures are defined in terms of themselves. A tree node holds a value and up to two smaller trees. Code that follows this shape is called structural recursion. The base case handles the empty structure (None), and the recursive case handles each smaller part.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def tree_sum(node):
if node is None:
return 0
return node.value + tree_sum(node.left) + tree_sum(node.right)
tree = Node(1, Node(2, Node(4)), Node(3))
print(tree_sum(tree)) # 10The stack depth equals the tree's height. The total number of calls is about the number of nodes.
Multiple Recursion and Repeated Work
tree_sum makes two recursive calls, and each call visits different data. Fibonacci also makes two calls, but they overlap. fib(n - 1) and fib(n - 2) both recompute fib(n - 3), and the same repetition continues further down.
def fib_naive(n):
if n < 2:
return n
return fib_naive(n - 1) + fib_naive(n - 2)
print(fib_naive(20)) # 6765The number of calls grows exponentially with n. A common mistake is to assume that two calls always cost 2n. They cost 2n only when the subproblems are disjoint, as they are in a tree traversal.
Comparing Time and Space Costs
Recursion uses one stack frame for each pending call, so its space cost is set by the maximum depth, not by the total number of calls.
| Solution | Time | Extra space |
|---|---|---|
| Recursive factorial | O(n) | O(n) stack |
| Iterative factorial | O(n) | O(1) |
| `tree_sum` | O(n nodes) | O(height) stack |
| Naive Fibonacci | O(φⁿ) | O(n) stack |
| Bottom-up Fibonacci loop | O(n) | O(1) |
Carrying State in an Accumulator
An accumulator is a parameter that carries the partial result down into each call. Without one, the function has to finish its work after the recursive call returns.
def sum_to_tail(n, acc=0):
if n == 0:
return acc
return sum_to_tail(n - 1, acc + n)
print(sum_to_tail(100)) # 5050In this version, the recursive call is the last thing the function does. That makes it a tail call.
Exercise
A balanced binary tree has 1,023 nodes. A degenerate tree, where every node has only a left child, also has 1,023 nodes. What maximum stack depth does tree_sum reach on each, and which one fails under CPython's default recursion limit?
Show answer
The balanced tree has height 10, so the depth is about 11 frames. The degenerate tree has height 1,023, so the depth is about 1,024 frames. That exceeds the default limit of 1000 and raises RecursionError. Both trees take O(n) time.