Sub topic 3
Depth and height
This chapter assumes you can read recursive Python and know what a call stack is. It uses the Node class and the five-node tree from the previous chapter.
Two measurements, two directions
Depth and height both count edges, but they start from opposite ends.
- The depth of a node is the number of edges on the path from the root down to that node. The root has depth 0.
- The height of a node is the number of edges on the longest path from that node down to a leaf. A leaf has height 0.
- The height of a tree is the height of its root.
Depth looks up toward the root. Height looks down toward the leaves.
Node 3 is a leaf, so its height is 0, even though the tree is taller on the other side.
Computing height
Height follows directly from the recursive structure. A node's height is one more than the taller of its two subtrees.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
root = Node(1, Node(2, Node(4), Node(5)), Node(3))
def height(node):
# Height in edges: an empty tree is -1, a single node is 0.
if node is None:
return -1
return 1 + max(height(node.left), height(node.right))
print(height(root)) # 2The base case returns -1 for an empty tree. That makes a leaf work out as 1 + max(-1, -1) = 0, which matches the edge-counting definition.
Computing depth
Depth is information that flows down, so you pass it as an argument. Each recursive call adds 1.
def depths(node, d=0, result=None):
if result is None:
result = {}
if node is None:
return result
result[node.value] = d
depths(node.left, d + 1, result)
depths(node.right, d + 1, result)
return result
print(depths(root)) # {1: 0, 2: 1, 4: 2, 5: 2, 3: 1}Height is computed on the way back up from the recursion. Depth is computed on the way down. This is why height uses a return value and depth uses a parameter.
Common errors
- Mixing conventions. Some texts count nodes instead of edges, so a single node has height 1 and an empty tree has height 0. Both are valid, but pick one. This tutorial counts edges, so a single node is 0 and an empty tree is -1.
- Swapping the two terms. The root always has depth 0. A leaf always has height 0.
- Returning 0 for
Nonewhile counting edges. This makes every height one too large. - Ignoring recursion limits. Python's default limit is about 1000 frames. A degenerate tree, where every node has one child, has height
n - 1. On such a tree,heightfails withRecursionErrorfor largen.
Each node is visited once, so height takes O(n) time. Its stack use is O(h), where h is the tree's height.
Exercise
Using the edge-counting convention, what are the height and depth of the node with value 2 in the example tree?
Show answer
Node 2 has depth 1, because one edge connects it to the root. Its height is 1, because the longest path down to a leaf (4 or 5) has one edge.