Diameter of Binary Tree

easy

Given the root of a binary tree, return the length of its diameter — the number of edges on the longest path between any two nodes. This path may or may not pass through the root.

The tree is given in level-order (breadth-first), using null for missing children.

Hints

For any node, the longest path bending at it is leftHeight + rightHeight edges.
The diameter is the maximum of that quantity over all nodes.
Compute height once bottom-up; return 1+max(L,R) upward but record L+R globally.

Common doubts

A parent can extend only one downward branch (so it wants max), but the diameter can bend and use both branches at this node (so the record uses the sum).
Edges — a path visiting k nodes has k−1 edges, so a single node has diameter 0.
No — it may lie entirely within a subtree, which is why every node is considered.

Interview follow-ups

Identical shape: return the best single downward branch, record the best bending path (there, a sum of values instead of a count of edges).
Track the node that achieved the maximum and its two deepest branches, then reconstruct by walking down both sides.

Fun facts

  • Diameter and maximum-path-sum are the same algorithm with a different quantity being combined at each node.
  • The 'return one branch, record both' idea generalizes to many tree DPs where a global answer bends at a node.

Asked at

AmazonFacebookGoogle
Frequently Sometimes Occasionally
Example 1
Input: root = [1, 2, 3, 4, 5]
Output: 3
The longest path is 4 -> 2 -> 1 -> 3 (or 5 -> 2 -> 1 -> 3), which has 3 edges.
Example 2
Input: root = [1, 2]
Output: 1
The path 1 -> 2 has a single edge.
Constraints

- The number of nodes is in the range [1, 10^4] - -100 <= Node.val <= 100

Solve this problem →