Longest Path in an Undirected Tree
Trees & GraphsAuto-graded · 16 test casesLast updated
Tests whether a candidate can find the longest edge-path in a tree using two linear-time traversals and reason about why the approach is correct.
Longest Path in an Undirected Tree
You have a tree of n nodes numbered 0 through n - 1, connected by n - 1 undirected edges. The longest path is the greatest number of edges on any simple path between two nodes in the tree. This value is also called the tree's diameter.
Write a function that returns the length of this longest path.
Input
n— the number of nodes.edges— a list of pairs[u, v], each describing one undirected edge.
Output
Return a single integer: the number of edges on the longest simple path.
Constraints
1 <= n <= 100_000len(edges) == n - 10 <= u, v < nandu != v- The graph is connected and acyclic (it is a valid tree).
Examples
Example 1
Input: longest_tree_path(5, [[0, 1], [1, 2], [1, 3], [3, 4]])
Output: 3
Example 2
Input: longest_tree_path(1, [])
Output: 0
Hints
Hint 1
Start a BFS from any node and note which node ends up farthest away. That node has a special property worth thinking about — it must lie at the end of some longest path.
Hint 2
Once you have that far endpoint, run a second BFS starting from it. The maximum distance found this time is the answer. Think about why two passes are enough rather than checking all pairs.
Hint 3
Watch out for the single-node case where there are no edges, and make sure you return an edge count, not a node count — those differ by one.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The algorithm relies on a two-BFS strategy and runs in O(n) time.
Step 1 — find a diameter endpoint.
Pick any starting node (node 0 is convenient). Run BFS and record the node a that sits farthest from the start. In a tree, every two nodes are connected by exactly one simple path, so BFS distances are exact edge counts. Node a turns out to be an endpoint of some longest path in the tree.
Why is that true? Suppose s–t is a longest path (a diameter). If a is not s or t, you can show — using the way paths overlap inside a tree — that some node is at least as far from a as s is from t. So the longest path reachable from a is at least as long as any diameter. Combined with the fact that no path can exceed the diameter, the second BFS must return exactly the diameter length.
A useful intuition: the farthest node from anywhere must sit at the tip of the tree's longest "arm." Anything shorter would mean there is a longer arm somewhere, contradicting how it was found.
Step 2 — measure the diameter.
Run a second BFS starting at a. The largest distance found equals the diameter.
Edge cases
n = 1, no edges: the only "path" is a single node, so the answer is0. The early return handles this.n = 2, one edge: the diameter is1. Both BFS passes work correctly.- Path-shaped tree (a line): the diameter is
n - 1. The first BFS might start in the middle of the line but will still land on one of its ends. - Star-shaped tree: the diameter is
2. From any leaf, any other leaf is exactly 2 edges away. - Single ties in "farthest node": any farthest node is a valid endpoint; the proof does not require uniqueness.
Why iterative BFS instead of recursive DFS?
With n up to 100,000 and a path-shaped tree, a recursive DFS can reach a call depth of 100,000 and raise a RecursionError in Python. BFS is fully iterative and avoids that problem entirely.
Complexity
- Time: O(n). Building the adjacency list is O(n), and each BFS visits every node and edge once.
- Space: O(n) for the adjacency list, the distance array, and the queue.
Reference Solution
from collections import deque
from typing import List
def longest_tree_path(n: int, edges: List[List[int]]) -> int:
if n <= 1:
return 0
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
def farthest(src):
"""BFS from src; return (farthest node reached, its distance)."""
dist = [-1] * n
dist[src] = 0
q = deque([src])
far = src
while q:
x = q.popleft()
if dist[x] > dist[far]:
far = x
for y in adj[x]:
if dist[y] < 0:
dist[y] = dist[x] + 1
q.append(y)
return far, dist[far]
a, _ = farthest(0) # first BFS: find one endpoint of a longest path
_, d = farthest(a) # second BFS: measure the full longest path from that endpoint
return d
dist[y] < 0 doubles as a visited check, avoiding a separate set. BFS processes nodes in non-decreasing distance order, so far is always updated to the current maximum correctly.