Measuring Tree Height Recursively

Tree height describes the longest root-to-leaf path. Decide whether the measure counts edges or nodes.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Use one convention
  2. Check a chain and a fork
  3. Write the unit before calculating any height
  4. Distinguish a longest branch from total work

Use one convention

For height in edges, a leaf has height zero. If an empty tree is assigned height minus one, an internal node can compute one plus the maximum child height. This pairs the base case with the recurrence.

Check a chain and a fork

Three nodes in a single chain have two edges of height. A root with two leaf children has height one even though it also contains three nodes. Counting nodes measures a different feature of the same structures.[1]

Write the unit before calculating any height

Under the edge-count convention, a leaf has height zero. A node with one child of height two and another of height zero has height three. Under the node-count convention, each corresponding nonempty height is one greater. Pick a convention before returning a height at an API boundary. See recursive tree size.

Edges:    A → B → C → D, plus A → E
Heights:  D=0, E=0, C=1, B=2, A=3
Node-count height at A: 4

Distinguish a longest branch from total work

Height takes the maximum over child branches. Summing their heights would make side branches extend the measured route. An implementation still examines all nodes when no height values are cached. Test a long path and a broad, shallow tree with the same total number of nodes.

References

  1. Jeff Erickson, Algorithms ↩