Sub topic 13
Depth versus height: how they relate
This chapter assumes you know the basic tree vocabulary (root, parent, child, leaf, subtree) and can read short recursive Python. It uses the edge-counting convention, where a leaf has height 0 and the root has depth 0.
Two measurements in opposite directions
Depth and height both count edges, but they start from opposite ends.
- Depth of a node is the number of edges on the path from the root down to that node.
- Height of a node is the number of edges on the longest path from that node down to a leaf in its subtree.
Depth looks up toward the root. Height looks down toward the leaves. Depth depends on where a node sits in the whole tree. Height depends only on the subtree below the node.
Reading both values from one tree
Take the example tree from earlier in this tutorial. A is the root. B has children E and F. C is a leaf. D has the child G.
| Node | Depth | Height |
|---|---|---|
| A | 0 | 2 |
| B | 1 | 1 |
| C | 1 | 0 |
| D | 1 | 1 |
| E | 2 | 0 |
| F | 2 | 0 |
| G | 2 | 0 |
The root always has depth 0, and its height equals the height of the tree. Every leaf has height 0, but leaves can have different depths. Here E, F, and G are at depth 2 and C is at depth 1.
The relationship between them
For any node, depth plus height is at most the height of the tree.
depth(n) + height(n) ≤ height(tree)
The longest path through a node goes from the root to the node (depth edges) and then down to its deepest leaf (height edges). That path cannot be longer than the longest root-to-leaf path in the tree.
Equality holds exactly when the node lies on a longest root-to-leaf path. Node B gives 1 + 1 = 2, which equals the tree height, so B is on a longest path. Node C gives 1 + 0 = 1, which is less than 2, so C is not.
Two further facts follow:
- Along any downward path, depth increases by 1 at each step and height decreases by at least 1.
- The deepest node in the tree has depth equal to the tree height.
A common error
Learners often compute height by counting up from a node to the root. That value is the depth. If a question asks for the height of C and you answer 1, you measured the wrong direction. C is a leaf, so its height is 0.
Checking the relationship in code
This snippet reuses height and depths from the previous sections and checks the inequality for every node.
def check(node, tree_height, depth_of):
assert depth_of[node.value] + height(node) <= tree_height
for child in node.children:
check(child, tree_height, depth_of)
check(tree, height(tree), depths(tree))
print("ok") # okExercise
A node has depth 3 and height 2. What is the smallest possible height of the whole tree, and when is it exactly that value?
Show answer
The smallest possible height is 5, because depth + height ≤ tree height. The tree height is exactly 5 when this node lies on a longest root-to-leaf path.