Sub topic 10
Recursion on Trees and Other Recursive Structures
This chapter assumes you can write a recursive function with a base case and a recursive case, and that you have seen tree recursion, where one function makes more than one recursive call. You should also be comfortable reading Python classes.
Earlier chapters split a list into its first element and the rest. That split is something you choose to do with the list. Some data structures are recursive by definition: part of a tree is itself a tree. For these structures, the shape of a correct function follows the shape of the data.
What Makes a Data Structure Recursive
A data structure is recursive when its definition refers to itself. A binary tree is one of two things:
- an empty tree, written as
Nonein Python, or - a node holding a value, a left subtree, and a right subtree, where each subtree is again a binary tree.
This definition has two cases, and they map straight onto the parts of a recursive function. The empty tree is the base case. The node case is the recursive case, and it makes one recursive call per subtree.
| Part of the definition | Part of the function |
|---|---|
| Empty tree (`None`) | Base case: return a fixed value |
| Node with left and right subtrees | Recursive case: call on `left` and `right`, then combine |
| Subtrees are smaller than the whole | Progress: every call gets closer to `None` |
Other recursive structures follow the same pattern. A linked list is either empty or a node followed by a linked list. A nested list is a list whose elements are numbers or other nested lists. A file system directory contains files and other directories.
Computing Tree Height
The height of a tree is the number of nodes on its longest path from the root down to a leaf. An empty tree has height 0.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = 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(height(tree)) # 3Read the recursive case using the leap of faith. Assume height(node.left) and height(node.right) return the correct heights of the subtrees. The height of the whole tree is then one more than the taller of the two. You don't need to trace into the subtrees to see that this is right.
Heights are computed from the bottom of the diagram up. Each None returns 0 straight away, and each node adds 1 to the larger result from its children. Every node is visited once, so the running time is O(n) for n nodes. The stack depth equals the tree's height. That is about log n for a balanced tree and n for a tree shaped like a chain.
One Template, Many Functions
Most tree functions use the same template. You fill in what to return for the empty tree and how to combine the node's value with the results from its subtrees.
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 tree_sum(node):
if node is None:
return 0
return node.value + tree_sum(node.left) + tree_sum(node.right)
def contains(node, target):
if node is None:
return False
return (node.value == target
or contains(node.left, target)
or contains(node.right, target))
def in_order(node):
if node is None:
return []
return in_order(node.left) + [node.value] + in_order(node.right)
tree = Node(1, Node(2, Node(4)), Node(3))
print(size(tree)) # 4
print(tree_sum(tree)) # 10
print(contains(tree, 3)) # True
print(contains(tree, 7)) # False
print(in_order(tree)) # [4, 2, 1, 3]contains uses or, which stops at the first True. The search therefore skips the rest of the tree as soon as it finds the target. In in_order, the position of [node.value] sets the traversal order. Move it to the front to get pre-order, or to the end to get post-order.
Common Errors
Testing children instead of the node
A common mistake is to check whether the children exist before making the recursive call:
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def size_buggy(node):
if node.left is None and node.right is None:
return 1
return 1 + size_buggy(node.left) + size_buggy(node.right)
tree = Node(1, Node(2, Node(4)), Node(3))
try:
print(size_buggy(tree))
except AttributeError as e:
print("AttributeError:", e)Node 2 has a left child but no right child. When it calls size_buggy(None), the code reads None.left and crashes. The bug never shows up on trees where every node has zero or two children. Making None the base case covers leaves, nodes with one child, and the empty tree with a single check.
Forgetting to use the recursive results
If you write height(node.left) on its own line and discard its return value, the function runs correctly but computes nothing useful. Each recursive call must feed into the value you return.
Assuming the tree is shallow
The stack depth of a tree function equals the tree's height. A tree built by inserting sorted values into an unbalanced binary search tree turns into a chain, so a tree with 10,000 nodes can exceed Python's recursion limit. A later chapter covers rewriting such functions with an explicit stack.
Other Recursive Structures
Linked lists
A linked list has one recursive reference per node, so its functions make one recursive call instead of two.
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)
chain = ListNode(3, ListNode(1, ListNode(4)))
print(length(chain)) # 3The code mirrors total(items[1:]) from the list chapter, but it doesn't copy anything. Following node.next takes O(1) time, while items[1:] copies the rest of the list on every call.
Nested lists
In a nested list, each element is either a plain value or another list. The function needs one case for each kind of element.
def nested_sum(items):
total = 0
for x in items:
if isinstance(x, list):
total += nested_sum(x)
else:
total += x
return total
def flatten(items):
result = []
for x in items:
if isinstance(x, list):
result.extend(flatten(x))
else:
result.append(x)
return result
data = [1, [2, [3, 4]], 5]
print(nested_sum(data)) # 15
print(flatten(data)) # [1, 2, 3, 4, 5]This version mixes a loop with recursion. The loop goes across the elements at one level, and recursion goes down into the sublists. Neither function has an explicit base case. The base case is a list with no sublists inside it, because then the loop finishes without making a recursive call. Each node in a general tree, such as a directory, can have any number of children, so code for those trees uses the same loop-plus-recursion pattern.
Choosing a Return Strategy
Tree functions either return a value built from the subtrees, as all the examples above do, or they add results to a shared accumulator. Returning values keeps each call independent and easy to test. Accumulating avoids the cost of building and concatenating many small lists. in_order above is O(n²) in the worst case because of list concatenation.
| Strategy | Example | Advantage | Cost |
|---|---|---|---|
| Return and combine | `in_order` returning lists | Each call is independent and easy to test | Builds a new list at every level |
| Shared accumulator | Appending to one list passed down | O(n) total work | Calls depend on shared mutable state |
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def in_order_fast(node, out=None):
if out is None:
out = []
if node is not None:
in_order_fast(node.left, out)
out.append(node.value)
in_order_fast(node.right, out)
return out
tree = Node(1, Node(2, Node(4)), Node(3))
print(in_order_fast(tree)) # [4, 2, 1, 3]
print(in_order_fast(tree)) # [4, 2, 1, 3]The default is None and a new list is created inside the function. Writing out=[] instead would share one list across all top-level calls, so the second call would print the values twice.
Exercise
Write count_leaves(node) that returns the number of leaves (nodes with no children) in a binary tree. What does it return for Node(1, Node(2, Node(4)), Node(3))?
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) + countleaves(node.right) It returns 2, for nodes 4 and 3. The None check comes first, so a node with one child safely calls countleaves(None), which returns 0.
Exercise
Write mirror(node) that returns a new tree with left and right swapped at every node, without modifying the original. What is in_order of the mirrored example tree?
Show answer
def mirror(node): if node is None: return None return Node(node.value, mirror(node.right), mirror(node.left)) The in-order traversal of the mirror is [3, 1, 2, 4], which is the original traversal reversed.
Exercise
Write maxdepth(items) for nested lists, where [1, 2] has depth 1, [1, [2]] has depth 2, and [] has depth 1. What is maxdepth([1, [2, [3, 4]], 5])?
Show answer
def maxdepth(items): deepest = 0 for x in items: if isinstance(x, list): deepest = max(deepest, maxdepth(x)) return 1 + deepest The answer is 3: the outer list, then [2, [3, 4]], then [3, 4].