← All problems

Diameter of Binary Tree

easy

Given the root of a binary tree, return the length (in edges) of the longest path between any two nodes. The path doesn't need to pass through the root.

At every node, the longest path through it is the sum of its left and right subtree depths — track the best of those sums while computing depth anyway.

Example

Input: root = [1, 2, 3, 4, 5]
Output: 3        // the path 4 → 2 → 1 → 3 (or 5 → 2 → 1 → 3)
Loading...