Skip to content

Diameter of a Binary Tree

EasyTrees
Decode it first. Clues, constraints, pattern and plan before any code.

The diameter of a binary tree is the number of edges on the longest path between any two nodes. That path may or may not pass through the root. Given the root, return the diameter.

Trees in the examples are written in level order (top to bottom, left to right), with null for a missing child, the same way the tests build them.

[1, 2, 3, 4, 5]  →  3   (4 -> 2 -> 1 -> 3, or 5 -> 2 -> 1 -> 3)
[1, 2]           →  1
[1]              →  0

An empty tree has diameter 0.

Constraints

  • 0 <= number of nodes <= 10^4
  • -100 <= Node.val <= 100