Imagine you're a network engineer tasked with finding the longest possible cable route in a tree-structured network. The diameter of a tree is the number of edges in the longest path between any two nodes - essentially the "widest span" of the tree.

Given an undirected tree with n nodes labeled from 0 to n-1, and a 2D array edges where each edges[i] = [ai, bi] represents a connection between nodes ai and bi, your goal is to find this maximum distance.

Key insight: Since it's a tree, there's exactly one path between any two nodes, and we need to find the pair of nodes that are furthest apart.

Input & Output

example_1.py — Linear Tree
$ Input: edges = [[0,1],[1,2],[2,3],[3,4]]
Output: 4
💡 Note: This forms a linear tree: 0-1-2-3-4. The longest path is from node 0 to node 4, which has 4 edges, so the diameter is 4.
example_2.py — Star Tree
$ Input: edges = [[0,1],[0,2],[0,3]]
Output: 2
💡 Note: This forms a star tree with node 0 at the center. The longest path is between any two leaf nodes (e.g., 1 to 2), which passes through the center and has 2 edges.
example_3.py — Single Node
$ Input: edges = []
Output: 0
💡 Note: Edge case: A tree with only one node has no edges, so the diameter is 0.

Visualization

Tap to expand
StartV1V2V3End1End2🏰 Royal Procession Route (Diameter)🌳 The Tree Kingdom: Finding the Longest Royal RouteBlue=Starting Village, Gold=Intermediate Villages, Green=Possible Endpoints
Understanding the Visualization
1
Start the expedition
Begin from any village (node 0) and explore to find the most distant village
2
Reach the frontier
The furthest village found must be at one end of the longest possible route
3
Start the royal procession
Begin the grand procession from this frontier village
4
Complete the journey
The furthest village reachable from the frontier is the other end - this distance is the diameter
Key Takeaway
🎯 Key Insight: Any furthest node from a starting point must be an endpoint of the diameter, making the two-pass approach both elegant and optimal!

Time & Space Complexity

Time Complexity
⏱️
O(n²)

We run DFS from each of the n nodes, and each DFS takes O(n) time to visit all nodes

n
2n
Quadratic Growth
Space Complexity
O(n)

Space for recursion stack and adjacency list representation of the tree

n
2n
Linearithmic Space

Constraints

  • n == edges.length + 1
  • 1 ≤ n ≤ 104
  • 0 ≤ aᵢ, bᵢ < n
  • aᵢ ≠ bᵢ
  • All (aᵢ, bᵢ) are distinct
  • The given input represents a valid tree
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
34.2K Views
High Frequency
~25 min Avg. Time
1.5K 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