Diameter of Binary Tree

25 min · diameterOfBinaryTree()

The widest route through a tree can hide entirely inside one branch. Looking only across the root misses it.

You're given the root of a binary tree. Its diameter is the greatest number of edges on any path between two nodes. Return that edge count.

A few ground rules:

  • The endpoints may be any two nodes.
  • The path doesn't have to pass through the root.
  • Count edges, not nodes: a path containing one node has length 0.
  • An empty tree and a single-node tree both return 0.

Constraints

  • 0 <= node count <= 10_000
  • -1_000 <= node.val <= 1_000

Hints

Try every meeting point

Imagine each node as the highest point of one candidate path. How far can that path descend into the left side and the right side?

Heights reveal the candidate

A subtree's height is the greatest number of nodes from its root down to a leaf. If the left height is L and the right is R, the path meeting at the current node uses L + R edges.

Don't calculate a height twice

A post-order traversal handles both children before their parent. Return the current height upward while updating the best diameter seen anywhere.

Follow-up

Could you also recover the two endpoint values without changing the O(n) time bound?

Visible cases

Examples

Example 1

ready
Input
root = [
  1,
  2,
  3,
  4,
  5
]
Expected
3
Why
the longest route uses three edges

Example 2

ready
Input
root = [
  1
]
Expected
0
Why
one node contains no edge

Example 3

ready
Input
root = []
Expected
0
Why
an empty tree has diameter zero

Interview signal

Asked at

AmazonGoogleMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite