Skip to content
StackDecode
TreesAnimated

Diameter of Binary Tree

The longest path is max over nodes of left height + right height.

Time

O(n)

Extra space

O(h)

Use it for

Longest path between any two nodes.

How it works

  1. The diameter is the number of edges on the longest path between any two nodes. It may not pass through the root.
  2. At every node, the longest path that bends at that node has length (left height + right height).
  3. Compute heights bottom-up and track the largest such sum.
  4. O(n).

Watch it run

Loading animation…