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
Visualization
Time & Space Complexity
We run DFS from each of the n nodes, and each DFS takes O(n) time to visit all nodes
Space for recursion stack and adjacency list representation of the tree
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