Sub topic 11
Height of a Node: Distance to the Deepest Leaf
This chapter assumes you can write recursive functions and that you know the tree vocabulary from earlier chapters: root, parent, child, leaf, and subtree. It also assumes you have met depth, which is measured from the root down.
What node height means
The height of a node is the number of edges on the longest downward path from that node to a leaf in its subtree. Depth looks up toward the root. Height looks down toward the leaves.
Two consequences follow from the definition:
- Every leaf has height 0, because the longest path from a leaf to a leaf is the empty path.
- The height of any other node is 1 plus the largest height among its children.
The second rule is why height is naturally recursive. A node only needs the heights of its children to know its own.
A worked example
Use the same tree as before. A is the root, B has children E and F, C is a leaf, and D has the child G.
Work from the bottom up:
- E, F, C, and G are leaves, so each has height 0.
- B has children with heights 0 and 0, so its height is 1 + 0 = 1.
- D has one child with height 0, so its height is 1.
- A has children with heights 1, 0, and 1, so its height is 1 + 1 = 2.
Notice that A's height uses the tallest child only. The short branch through C does not change it.
Computing height in code
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 argument handles a leaf. A leaf has no children, so max would otherwise fail on an empty sequence. With the default, a leaf returns 1 + (-1) = 0, which matches the definition.
Common errors
- Mixing up height and depth. In the example, node B has depth 1 and height 1, but node E has depth 2 and height 0. They answer different questions.
- Using the first child instead of the tallest. Height needs the maximum over all children, not the height of one child.
- Forgetting the convention. Some sources count nodes instead of edges, which makes a leaf have height 1. Check which convention a source uses before comparing numbers.
Exercise
A node X has three children. Their heights are 4, 0, and 2. What is the height of X, and what is the height of X's subtree if you remove the child with height 4 (edge-counting convention)?
Show answer
The height of X is 1 + max(4, 0, 2) = 5. After removing the tallest child, the height is 1 + max(0, 2) = 3.