Advanced topics · Exercise 93 of 100

Binary tree diameter

The diameter of a nonempty tree is the length of its longest simple path, measured here in edges. At each node, add the lengths of the longest downward paths through its left and right children, using zero for a missing side. The largest sum is the diameter because every path has a highest node where its two sides meet.

Try it yourself

Node 1 has only child 2. From 2, one child chain runs 2–3–5–7 and the other runs 2–4–6–8. There are no other nodes. What is the diameter in edges?

One-step hint

From the bottom of each chain, count edges back to node 2. Sketch the routes between the two chain ends and from either end to node 1.

Worked solution
  1. From node 2, the path down to 7 has three edges and the path down to 8 also has three. Joining them gives a path through 2 with six edges.
  2. A path from 1 reaches either tip in only four edges, and a path within one child chain uses at most three. The diameter is therefore 6.
DSA compiler