Tree Diameter Problem
Description
LeetCode Problem 1245.
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] = [a_i, b_i] indicates that there is an undirected edge between nodes a_i and b_i in the tree.
Return the diameter of the tree.
Example 1:

Input: edges = [[0,1],[0,2]]
Output: 2
Explanation: The longest path of the tree is the path 1 - 0 - 2.
Example 2:

Input: edges = [[0,1],[1,2],[2,3],[1,4],[4,5]]
Output: 4
Explanation: The longest path of the tree is the path 3 - 2 - 1 - 4 - 5.
Constraints:
n == edges.length + 11 <= n <= 10^40 <= a_i, b_i < na_i != b_i
Solution
Approach: Two Searches From the Farthest Node
A useful fact about trees: starting from any node, the node farthest from it is an end of some longest path. So:
- Search from node
0and find the farthest nodea. - Search from
aand find the farthest distance. That distance is the diameter.
This is the classic two-search argument: if the farthest node a were not an end of a longest path, then swapping one end of a longest path for the route to a would give an even longer path, which is impossible.
Each search is a walk over the tree that tracks the distance from the start and never goes back to the parent. Since a tree has no cycles, that visits each node once. We use an explicit stack of (node, parent, distance) instead of recursion: a path-shaped tree with 104 nodes would make a recursive walk 104 calls deep, which overflows the default stack in some languages.
A tree with one node has no edges, and both searches return distance 0.
Complexity: O(n) time and O(n) space for the adjacency lists and the stack.
class Solution:
def treeDiameter(self, edges: List[List[int]]) -> int:
n = len(edges) + 1
g = [[] for _ in range(n)]
for a, b in edges:
g[a].append(b)
g[b].append(a)
def farthest(start):
"""The node farthest from start, and its distance (an explicit stack, no recursion)."""
node, dist = start, 0
stack = [(start, -1, 0)] # (node, parent, distance from start)
while stack:
i, parent, d = stack.pop()
if d > dist:
node, dist = i, d
for j in g[i]:
if j != parent:
stack.append((j, i, d + 1))
return node, dist
a, _ = farthest(0) # a is one end of a longest path
return farthest(a)[1]