Sub topic 15
Computing depth and height in code
This chapter assumes you can write recursive functions and that you know the terms root, leaf, and subtree from earlier chapters. Both measurements below count edges, so the root has depth 0 and a leaf has height 0.
The example tree
Each node stores a value and a list of children. A node with an empty list is a leaf.
class Node:
def __init__(self, value, children=None):
self.value = value
self.children = children or []
def is_leaf(self):
return not self.children
# A is the root. Leaves are C, E, F, and G.
tree = Node("A", [
Node("B", [Node("E"), Node("F")]),
Node("C"),
Node("D", [Node("G")]),
])Height flows upward
The height of a node depends on its subtree, so you must know the children's heights first. The recursion therefore returns values from the bottom up. The height of a node is one more than the largest height among its children.
def height(node):
# Edge-counting convention: a leaf has height 0.
return 1 + max((height(child) for child in node.children), default=-1)
print(height(tree)) # 2
print(height(tree.children[0])) # 1 (node B)
print(height(tree.children[1])) # 0 (node C, a leaf)The default=-1 argument handles leaves. A leaf has no children, so max falls back to -1, and 1 + (-1) gives 0. Without default, max raises ValueError on an empty sequence.
Depth flows downward
Depth depends on the path from the root, so the information travels the other way. Each call receives its parent's depth and adds one.
def depths(node, depth=0, result=None):
# The root has depth 0. Each step down adds one edge.
if result is None:
result = {}
result[node.value] = depth
for child in node.children:
depths(child, depth + 1, result)
return result
print(depths(tree))
# {'A': 0, 'B': 1, 'E': 2, 'F': 2, 'C': 1, 'D': 1, 'G': 2}The code creates the result dictionary inside the function instead of using result={} as the default. A mutable default would be shared across calls and would mix results from different trees.
Common errors
- Using the wrong base case. Returning 0 for a node with no children is correct. Returning 1 gives the node-counting convention, and your numbers are off by one.
- Mixing directions. Computing depth bottom-up or height top-down needs extra bookkeeping. Pass depth down as an argument and return height up as a value.
- Reusing a mutable default. Always create the dictionary inside the function.
Converting conventions
Some sources count nodes instead of edges. Under that rule a leaf has height 1 and the root has depth 1. To convert, add 1 to an edge-based value or subtract 1 from a node-based one. For the example tree, the edge-based height is 2 and the node-based height is 3.
Both functions visit every node once, so they run in O(n) time. Recursion depth equals the tree height, which matters for very skewed trees.
Exercise
Write max_depth(node) that returns the largest depth of any node, using the edge-counting convention. What does it return for the example tree, and how does it compare with height(tree)?
Show answer
def maxdepth(node, depth=0): return max([depth] + [maxdepth(c, depth + 1) for c in node.children]). It returns 2 for the example tree, which equals height(tree). The height of the root is the depth of the deepest node.