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 - Two DFS Approach INPUT Tree Structure: 1 0 2 4 3 edges = [[0,1],[1,2], [2,3],[1,4]] n = 5 nodes (0 to 4) 4 edges (n-1) Undirected Tree ALGORITHM STEPS 1 First DFS from node 0 Find farthest node Result: node 3 (dist=3) 2 Second DFS from node 3 Find farthest from endpoint Result: node 0 or 4 3 Track max distance Path: 0--1--2--3 or 4--1--2--3 Max dist = 3 edges 4 Return diameter Max distance = diameter DFS Traversal: 0 1 2 3 4 Diameter Path FINAL RESULT Longest Path Highlighted: 1 0 2 4 3 1 2 3 Output: 3 OK - Diameter = 3 edges Path: 0 -- 1 -- 2 -- 3 Key Insight: The Two DFS approach works because the farthest node from any node is always an endpoint of the diameter. First DFS finds one endpoint, second DFS from that endpoint finds the diameter. Time: O(n), Space: O(n). BFS can also be used instead of DFS with the same complexity. TutorialsPoint - Tree Diameter | Two DFS - Optimal Tree Diameter
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