InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Trees

Diameter of Binary Tree

easy Original ↗ 00:00

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], so O(n) is expected; the O(n^2) recompute-heights approach is the brute force.
  • -100 <= Node.val <= 100. Values do not matter; only the tree shape does.

Think about it first

Hint 1 Every path has a unique highest node where it bends. From that node, the path is the longest chain going down the left plus the longest chain going 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. Which 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug