Sub topic 6
Recursion on Recursive Data: Lists and Trees
This chapter assumes you can write recursive functions with a base case and a recursive case, and that you know each call adds a frame to the call stack. It also assumes you have seen Python classes with attributes. Earlier chapters used recursion on numbers, where n counts down to 0. Here the input is a data structure that contains smaller copies of itself. For data like this, recursion is often the most direct way to write the code.
What Makes Data Recursive
A recursive data structure is a type whose definition refers to itself. Two standard examples:
- A linked list is either empty (
None) or a node holding a value and a link to another linked list. - A binary tree is either empty (
None) or a node holding a value, a left binary tree, and a right binary tree.
Each definition has two parts. The first is a case with no self-reference, which is the empty structure. The second is a case that contains one or more smaller structures of the same type. A recursive function has the same two parts: the empty case becomes the base case, and each self-reference in the definition becomes a recursive call. Writing functions this way is called structural recursion, because the shape of the code follows the shape of the data.
The None boxes in the diagram matter. Recursive functions over trees spend about half their calls on these empty subtrees, and those calls are where the base case runs.
Linked Lists: One Self-Reference, One Recursive Call
A linked list node has a single link to the rest of the list, so a function over it makes a single recursive call.
class ListNode:
def __init__(self, value, next=None):
self.value = value
self.next = next
def length(node):
if node is None:
return 0
return 1 + length(node.next)
def total(node):
if node is None:
return 0
return node.value + total(node.next)
def length_loop(node):
count = 0
while node is not None:
count += 1
node = node.next
return count
items = ListNode(3, ListNode(1, ListNode(4)))
print(length(items)) # 3
print(total(items)) # 8
print(length_loop(items)) # 3The recursive and iterative versions are equally clear here. A linked list is linear, so the loop needs only one cursor (node) and one running value (count). The recursive version still has a cost: it uses one stack frame per node. A linked list with 5,000 nodes passed to length exceeds CPython's default recursion limit of 1,000. The loop handles it without trouble. For flat, linear structures, recursion makes the code look tidy, but the loop can handle any length.
Nested Lists: Recursion Inside a Loop
Python lists can contain other lists to any depth. Such a list is either a plain value (an atom) or a list of nested lists. The number of children varies from node to node, so the usual pattern is a loop over the children with a recursive call on each one.
def flatten(data):
if not isinstance(data, list):
return [data]
result = []
for item in data:
result.extend(flatten(item))
return result
def nesting_depth(data):
if not isinstance(data, list):
return 0
if not data:
return 1
return 1 + max(nesting_depth(item) for item in data)
nested = [1, [2, [3, 4]], [], 5]
print(flatten(nested)) # [1, 2, 3, 4, 5]
print(nesting_depth(nested)) # 3This combination of a loop and recursion is normal. The loop moves across the children of one node, and the recursion moves down into each child. Neither one could replace the other here without extra bookkeeping.
nesting_depth handles the empty list as its own case because max() raises ValueError on an empty sequence. Edge cases like this one show up when a node can have zero children.
Gotcha: Strings Contain Themselves
If you generalize flatten to any iterable, you can create a structure that never reaches the base case:
def flatten_any(data):
try:
iterator = iter(data)
except TypeError:
return [data]
result = []
for item in iterator:
result.extend(flatten_any(item))
return result
print(flatten_any([1, (2, 3), {4}])) # [1, 2, 3, 4]
try:
flatten_any(["ab"])
except RecursionError:
print("RecursionError: 'a' iterates to 'a' forever")Iterating over "ab" yields "a", and iterating over "a" yields "a" again. The input never gets smaller, so the recursion never ends. Structural recursion terminates only when every recursive call receives a strictly smaller piece of the structure.
Binary Trees: Two Self-References, Two Recursive Calls
A tree node has two subtrees, so most tree functions make two recursive calls and combine the results.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def size(node):
if node is None:
return 0
return 1 + size(node.left) + size(node.right)
def height(node):
if node is None:
return 0
return 1 + max(height(node.left), height(node.right))
def tree_sum(node):
if node is None:
return 0
return node.value + tree_sum(node.left) + tree_sum(node.right)
def inorder(node):
if node is None:
return []
return inorder(node.left) + [node.value] + inorder(node.right)
def mirror(node):
if node is None:
return None
return Node(node.value, mirror(node.right), mirror(node.left))
tree = Node(1, Node(2, Node(4)), Node(3))
print(size(tree)) # 4
print(height(tree)) # 3
print(tree_sum(tree)) # 10
print(inorder(tree)) # [4, 2, 1, 3]
print(inorder(mirror(tree))) # [3, 1, 2, 4]All five functions have the same structure, and only the combining step changes:
| Function | Base case returns | Combining step |
|---|---|---|
| `size` | `0` | `1 + left + right` |
| `height` | `0` | `1 + max(left, right)` |
| `tree_sum` | `0` | `value + left + right` |
| `inorder` | `[]` | `left + [value] + right` |
| `mirror` | `None` | new node with subtrees swapped |
Why Trees Favor Recursion
A loop over a linked list keeps one cursor. A loop over a tree cannot do that. When it goes left, it has to remember to come back for the right subtree later. Recursion stores that pending work in the call stack for you: each frame holds a node whose right subtree still needs a visit. A later chapter makes this bookkeeping visible by replacing the call stack with an explicit list.
The two calls in these functions do not repeat work. Each node is visited once, so size, height, and tree_sum run in O(n) time. (inorder as written also copies lists at each level, which can cost O(n²) on a degenerate tree. Appending to one shared output list avoids this.) This is different from the repeated work in multiple recursion on overlapping subproblems, covered in the next chapter. A tree's subtrees do not overlap, so there is nothing to cache.
Following One Path: Binary Search Trees
Some tree functions need only one branch. In a binary search tree (BST), every value in the left subtree is smaller than the node's value and every value in the right subtree is larger. A search therefore follows a single path:
def bst_contains(node, target):
if node is None:
return False
if target == node.value:
return True
if target < node.value:
return bst_contains(node.left, target)
return bst_contains(node.right, target)
bst = Node(5, Node(3, Node(1), Node(4)), Node(8, None, Node(9)))
print(bst_contains(bst, 4)) # True
print(bst_contains(bst, 7)) # FalseEach recursive call here is the last thing the function does, and its result is returned directly. Functions of this kind turn into simple loops, as a later chapter shows.
Stack Depth Follows Height, Not Size
For tree recursion, the maximum number of frames on the stack at once equals the tree's height, not its node count. A balanced tree with a million nodes has height about 20, so recursion is safe. A degenerate tree, where every node has only a right child, has height equal to its size and behaves like a linked list. Inserting already-sorted keys into an unbalanced BST produces exactly this shape. A few thousand sorted inserts followed by a recursive height call will raise RecursionError.
| Structure | Recursive calls per node | Max stack depth |
|---|---|---|
| Linked list of n nodes | 1 | n |
| Nested list | one per child | nesting depth |
| Balanced binary tree | 2 | about log₂ n |
| Degenerate binary tree | 2 | n |
Common Errors
- Checking children instead of the node. Writing
if node.left is None and node.right is None:as the only base case treats leaves as the base case. The function then crashes on an empty tree and on a node that has exactly one child, because it calls itself withNoneand readsNone.left. Makenode is Nonethe base case. - Dropping a recursive result.
size(node.left)on its own line computes a value and discards it. Every recursive result must feed into the combining step. - Mutable default accumulators.
def collect(node, out=[])reuses the same list across separate top-level calls, so results from one call leak into the next. Useout=Noneand create a new list inside the function. - Assuming balance. Recursion on user-supplied or sorted input can produce degenerate trees. If the height is not bounded, plan for an iterative version.
Exercise
Write a recursive function count_leaves(node) for the Node class that returns the number of nodes with no children. What does it return for Node(1, Node(2, Node(4)), Node(3))?
Show answer
Use two base cases: if node is None: return 0, then if node.left is None and node.right is None: return 1. Otherwise return count_leaves(node.left) + count_leaves(node.right). The leaves are 4 and 3, so it returns 2. The leaf test is safe here because it comes after the None check.
Exercise
A function def max_value(node): return max(node.value, max_value(node.left), max_value(node.right)) has the base case if node is None: return 0. Give an input where it returns the wrong answer, and fix it.
Show answer
For a tree whose values are all negative, such as Node(-5, Node(-2)), it returns 0 because the base case adds a value that is not in the tree. Return float('-inf') for None, which is the identity element for max. Alternatively, raise an error for an empty top-level tree.
Exercise
You insert the keys 1 through 5000 in increasing order into an unbalanced BST and then call the recursive height. What happens in CPython with default settings, and why?
Show answer
It raises RecursionError. Sorted inserts make every node a right child, so the tree's height is 5000. Recursive height keeps one frame per level on the stack, which exceeds the default limit of about 1000.