Sub topic 6
Recursion on Recursive Data: Lists and Trees
This chapter assumes you can write a recursive function with a base case and a recursive case, and that you know each call adds a frame to the call stack. It also uses simple Python classes.
Data That Contains Itself
A recursive data structure is defined in terms of a smaller version of itself. A linked list is either empty, or a node holding a value and a link to another linked list. A binary tree is either empty, or a node holding a value and links to two smaller trees.
The definition already tells you how to write the function. Each "either" in the definition becomes a branch in the code:
- The empty case (
None) becomes the base case. - The node case becomes the recursive case, with one recursive call for each self-referencing part.
Writing a function this way is called structural recursion. The recursion follows the shape of the data, so each call works on a strictly smaller piece, and the function always reaches the base case on finite input.
Linked Lists: One Recursive Call
A list node has one link, so a structurally recursive list function makes one 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)
nums = ListNode(3, ListNode(1, ListNode(4)))
print(length(nums)) # 3
print(total(nums)) # 8Both functions share the same skeleton and differ only in what they combine. The stack depth equals the list length plus one, because the final call handles None. A list with 10,000 nodes therefore needs about 10,000 frames, which is more than CPython's default limit allows.
Binary Trees: Two Recursive Calls
A tree node has two links, so the function makes two calls and combines their 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))
tree = Node(1, Node(2, Node(4)), Node(3))
print(size(tree)) # 4
print(height(tree)) # 3For trees, the stack depth depends on the tree's height, not its size. A balanced tree with a million nodes is only about 20 levels deep. A degenerate tree, where every node has only one child, behaves like a linked list, so its depth equals its size.
Why This Matters for Iteration
A list function makes one recursive call, so it maps directly to a while node is not None loop. A tree function makes two calls, so after the first call finishes it must come back and make the second. A single loop variable cannot remember that pending work. Later chapters show how an explicit stack stores it.
Exercise
Write a structurally recursive function count_leaves(node) that returns the number of leaf nodes in a binary tree. A leaf is a node with no children. What does it return for the example tree above?
Show answer
def countleaves(node): if node is None: return 0 if node.left is None and node.right is None: return 1 return countleaves(node.left) + count_leaves(node.right) For the example tree it returns 2, because the leaves are 4 and 3. Two base cases are needed: an empty tree contains no leaves, and a childless node counts as one leaf.
Exercise
A binary search tree is built by inserting 1, 2, 3, ..., 5000 in that order with no rebalancing. Will calling height() on it raise a RecursionError in CPython with default settings? Why?
Show answer
Yes. Each value becomes the right child of the previous one, so the tree's height is 5000. height() needs about 5000 nested frames, which is more than the default limit of 1000.