InterviewPrepKit

Home / Coding / Trees

Diameter of Binary Tree

easy Original β†—
Solving tips
  • Key insight: every path bends at a unique highest node, where its length is height(left) + height(right) in edges.
  • Use one post-order DFS that RETURNS a node's height while updating a global max as a side effect β€” computing heights fresh per node is the O(n^2) trap.
  • The recursion must return a single downward chain (1 + max(left, right)), while the bent path (left + right + 2) only updates the running best β€” never return the bent value. O(n) time, O(h) space.
  • Pitfall: the answer counts EDGES not nodes (a single node has diameter 0), and the longest path need not pass through the root.

Problem

Given the root of a binary tree, return its diameter: the number of edges on the longest path between any two nodes in the tree. The path may or may not pass through the root, and it never repeats a node.

Key detail: the answer counts edges, not nodes β€” a path through k nodes has length k βˆ’ 1.

Examples

Example 1

Input:  root = [1,2,3,4,5]

        1
       / \
      2   3
     / \
    4   5

Output: 3

One longest path is 4 β†’ 2 β†’ 1 β†’ 3 (equally 5 β†’ 2 β†’ 1 β†’ 3): 4 nodes, 3 edges.

Example 2

Input:  root = [1,2]
Output: 1

Only one edge exists.

Example 3

        1
       /
      2
     / \
    3   4
   /     \
  5       6

Output: 4

The longest path 5 β†’ 3 β†’ 2 β†’ 4 β†’ 6 bends at node 2 and never touches the root.

Constraints

  • The number of nodes is in [1, 10^4] β€” O(n) is expected; the O(n^2) recompute-heights approach is the brute force to beat.
  • -100 <= Node.val <= 100 β€” values are irrelevant; only shape matters.

Think about it first

Hint 1 Any path has a unique highest node where it "bends". Seen from that node, the path is a longest chain down the left plus a longest chain down the right.
Hint 2 So for each node, the best path bending there has length `height(left) + height(right)` in edges. Trying every node with a fresh height computation works β€” but repeats work. What single traversal computes every node's height exactly once?
Hint 3 Post-order DFS: return the node's height to the parent, and as a side effect update a global maximum with `left_height + right_height` at every node.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.