Skip to main content
LeetCode 1245, Medium. Topics: Tree, Depth-First Search, Breadth-First Search, Graph, Topological Sort. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 25 parametrized pytest cases, and a playground notebook:

Problem

The diameter of a tree is the number of edges in the longest path in that tree. There is an undirected tree of n nodes labeled from 0 to n - 1. You are given a 2D array edges where edges.length == n - 1 and edges[i] = [ai, bi] indicates that there is an undirected edge between nodes ai and bi in the tree. Return the diameter of the tree.

Examples

Example 1
Explanation: The longest path of the tree is the path 1 - 0 - 2. Example 2
Explanation: The longest path of the tree is the path 3 - 2 - 1 - 4 - 5.

Constraints

  • n == edges.length + 1
  • 1 <= n <= 10^4
  • 0 <= ai, bi < n
  • ai != bi

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026