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.

Input & Output

Example 1 — Linear Tree
$ Input: edges = [[0,1],[1,2],[2,3],[1,4]]
Output: 3
💡 Note: The tree forms a shape where longest path is from node 4 to node 3 (or 3 to 4), going through nodes 4→1→2→3, which has 3 edges.
Example 2 — Simple Path
$ Input: edges = [[0,1],[0,2]]
Output: 2
💡 Note: Tree with 3 nodes: 1-0-2. The diameter is the path from node 1 to node 2, which has 2 edges (1→0→2).
Example 3 — Single Edge
$ Input: edges = [[0,1]]
Output: 1
💡 Note: Tree with only 2 nodes connected by 1 edge. The diameter is simply that one edge.

Constraints

  • n == edges.length + 1
  • 1 ≤ n ≤ 104
  • 0 ≤ ai, bi < n
  • ai ≠ bi
  • The given input represents a valid tree.

Visualization

Tap to expand
Tree Diameter: Finding the Longest Path01234Longest Path: 3→1→2→4Input: edges = [[0,1],[1,2],[2,3],[1,4]]Output: 3 (number of edges in longest path)
Understanding the Visualization
1
Input Tree
Given edges representing connections between nodes
2
Find Longest Path
Identify the path with maximum number of edges
3
Count Edges
Return the number of edges in longest path
Key Takeaway
🎯 Key Insight: Use two DFS/BFS traversals to efficiently find tree diameter in O(n) time
Asked in
Facebook 15 Amazon 12 Google 8 Microsoft 6
89.4K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen