Skip to content
CodeShare
All problems

Diameter of Binary Tree

Find the longest path between any two nodes of a tree.

EasyTrees

Given the root of a binary tree, return the length of its diameter: the number of edges on the longest path between any two nodes. The path doesn't have to pass through the root.

Trees are written level by level, with null for a missing child.

Examples

Example 1
Input
root = [1, 2, 3, 4, 5]
Output
3
Why
The path 4 → 2 → 1 → 3 (or 5 → 2 → 1 → 3) has 3 edges.
Example 2
Input
root = [1, 2]
Output
1

Constraints

  • The tree has between 1 and 10^4 nodes.
  • -100 <= Node.val <= 100