Sub topic 12
Height of a Tree
This chapter assumes you can read recursive Python and know what a node, a parent, a child, and a leaf are. It also assumes you know that depth is the number of edges from the root down to a node. Here you will define the height of a tree and compute it.
From node height to tree height
The height of a node is the number of edges on the longest downward path from that node to a leaf. A leaf has height 0.
The height of a tree is the height of its root. Equivalently, it is the largest depth of any node. The tree is only as tall as its deepest leaf.
In this tree the longest downward path from A is A, B, E, which has 2 edges. So the tree height is 2. Each node is labeled with its height (h) and depth (d). The deepest leaves (E, F, G) have depth 2, and that matches the height of the root.
Computing it
Height is computed bottom-up. A node's height is one more than the tallest child's height. A leaf has no children, so the formula needs a base value for "no children".
class Node:
def __init__(self, value, children=None):
self.value = value
self.children = children or []
def height(node):
# Edge-counting convention: a leaf has height 0.
return 1 + max((height(child) for child in node.children), default=-1)
tree = Node("A", [
Node("B", [Node("E"), Node("F")]),
Node("C"),
Node("D", [Node("G")]),
])
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 handles a leaf. With no children, max returns -1, and 1 + (-1) gives 0. Without default, max raises ValueError on an empty sequence.
The function visits every node once, so it takes time proportional to the number of nodes. The recursion depth equals the tree height, which matters for very skewed trees.
Common errors
- Confusing height with depth. Depth is measured from the root down. Height is measured from a node down. The root has depth 0 and the largest height. A deepest leaf has the largest depth and height 0.
- Mixing conventions. Some sources count nodes instead of edges, so a single node has height 1 and the example tree has height 3. Check which convention a source uses. To convert, add or subtract 1.
- Taking the shortest child path. Height uses the longest path, so use
max, notmin. - Forgetting the base case. A function that assumes every node has a child fails on leaves.
Exercise
A tree has root R with two children, X and Y. X has one child, Z. Z has one child, W. What is the height of the tree under the edge-counting convention, and what is it under the node-counting convention?
Show answer
The longest downward path is R, X, Z, W. That is 3 edges, so the height is 3 under the edge convention. It has 4 nodes, so the height is 4 under the node convention.