Sub topic 10
Recursion on Trees and Other Recursive Structures
This chapter assumes you can write recursive functions on lists, and that you know tree recursion, where one call makes several recursive calls. It also assumes you can read a simple Python class.
Data That Contains Itself
A recursive data structure is one that is defined in terms of smaller copies of itself. A binary tree is either empty or a node holding a value plus two binary trees, called its left and right subtrees. Because the data is defined this way, the code that processes it can follow the same shape:
- The empty tree is the base case.
- A node is the recursive case. You recurse into each subtree and combine the results with the node's own value.
You saw a simpler version of this with lists, where a list is either empty or a first element followed by a smaller list. A tree works the same way, except each node has two smaller pieces instead of one.
Computing 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. A node's height is one more than the height of its taller subtree.
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))
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(height(tree)) # 3
print(tree_sum(tree)) # 10Apply the leap of faith here. When you write height, assume that height(node.left) already returns the correct answer for the left subtree. Your only job is to combine the two subtree answers with the current node. You don't need to trace how the deeper calls work.
The Pattern
Most tree functions follow one template:
| Part | `height` | `tree_sum` |
|---|---|---|
| Empty tree returns | `0` | `0` |
| Combine step | `1 + max(l, r)` | `value + l + r` |
Each node is visited exactly once, so these functions run in O(n) time for a tree with n nodes. The recursion goes only as deep as the tree is tall, so the stack depth equals the height. That is about log n for a balanced tree. For a tree that degenerates into a chain, it is n.
Common Errors
- Dropping a subtree's result: calling
height(node.left)without using its return value throws that work away. - Off-by-one definitions: some sources count height in edges, so a single node has height 0. Pick one definition and make the base case match it. With the edge count, an empty tree returns
-1. - Combining in the wrong place: the combine step belongs after both recursive calls have returned. It cannot use subtree results before they exist.
Exercise
Write a recursive function count_leaves(node) that returns the number of leaves, which are nodes with no children. What does it return for the example tree?
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 nodes 4 and 3 are the leaves. The None check comes first so that a node with only one child stays safe.
Exercise
What is the maximum recursion depth of height() on a tree where every node has only a left child and there are 500 nodes?
Show answer
About 500 frames for the nodes, plus one more call that reaches None. The tree is a chain, so its height equals n and the stack depth grows linearly.