Skip to interview prep
Apexed

59. Diameter of a Binary Tree

MediumTrees

Return the number of edges on the longest path between any two nodes of the tree. The path may or may not pass through the root.

A binary tree is passed as TreeNode objects with val, left and right. The tests write trees in level order, with null for a missing child.

Example 1

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

Constraints

  • 1 ≤ nodes ≤ 10⁴

Tab indents · Ctrl/⌘ + Enter runs · Esc then Tab leaves the editor

Run checks these cases; the expected output comes from the reference solution. Submit judges all 4 hidden and sample tests.

Code runs only in your browser in an isolated sandbox. Progress and submissions are saved on this device.

Diameter of a Binary Tree — coding interview practice — Apexed