Trees and binary search trees · Exercise 36 of 100

Diameter of a binary tree

The diameter is the number of edges on the longest path between any two nodes. At each node, add the lengths in edges of the deepest downward paths on its left and right, using zero for a missing side. Take the largest sum anywhere in the tree because the longest path can lie entirely below the root.

Try it yourself

Root 50 has just one child, 20. From 20, the left branch runs through 10, then 5, then 2. Its right branch runs through 30, then 35, then 40. There are no other nodes. What is the diameter in edges?

One-step hint

Draw both branches below 20. Trace between their deepest leaves and compare that edge count with the longest route starting at 50.

Worked solution
  1. From 20, it takes three edges to reach 2 and three to reach 40. Joining those branches gives a path of six edges.
  2. A path from 50 reaches either tip in four edges, and a path confined to one branch is shorter still. The longest path therefore has 6 edges.
DSA compiler