← DiffPush

Diameter of Binary Tree

Standard Bar Binary Trees · Medium Problems O(n) · O(h)

The Longest Cable Run

A fiber crew maps junction boxes laid out as a binary tree and must budget the longest possible cable run between any two boxes, following connections only. The run doesn't have to touch the head junction — sometimes the longest haul arcs between two deep branches. Every junction reports the two deepest descents around it, and the best combination anywhere wins the budget.

Input: The root of a binary tree given as a level-order array where null marks a missing child.

Output: Return an integer: the length (in edges) of the longest path between any two nodes.

Constraints

Examples

Example 1

Input: {"tree":[1,2,3,4,5]}
Output: 3
The path 4 -> 2 -> 1 -> 5 (or 3) covers 3 edges.

Example 2

Input: {"tree":[1,2]}
Output: 1
The only two-node path is a single edge.

Solve this in your browser →

Also on LeetCode ↗