Find the Longest Path in an Undirected Tree
Trees & GraphsModel answerLast updated
Given a tree as an adjacency list, return the sequence of nodes forming its diameter — the longest simple path between any two nodes.
Problem
You are given an undirected tree with n nodes labeled 0 through n-1, described by a list of n-1 undirected edges. The diameter of a tree is the length (in edges) of the longest simple path between any pair of nodes.
Write a function that returns any one path whose length equals the diameter. The path should be given as an ordered list of node labels from one endpoint to the other.
def longest_tree_path(n: int, edges: List[List[int]]) -> List[int]:
Constraints
2 ≤ n ≤ 10,000edgeshas exactlyn-1entries and forms a valid tree (connected, no cycles)- Node labels are integers in
[0, n-1]
Examples
Example 1
n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
Output: [0, 1, 2, 3, 4] (or its reverse)
The tree is a straight line; the diameter spans all five nodes.
Example 2
n = 4, edges = [[0,1],[1,2],[1,3]]
Output: [0, 1, 2], [0, 1, 3], or [2, 1, 3] — any one is acceptable.
Node 1 is the center; every leaf-to-leaf path has length 2, which is the diameter.
Notes
- Any valid diameter path is accepted; you do not need to find a unique one.
- Consider trees with only two nodes, and trees shaped like a star.
Hints
Hint 1
Start a BFS from any node. The node it reaches last (farthest away) is guaranteed to be one endpoint of some diameter path — can you convince yourself why?
Hint 2
Run a second BFS from that endpoint, this time recording each node's parent. The farthest node in this sweep is the other endpoint.
Hint 3
To reconstruct the path, follow the parent pointers from the second endpoint back to the first. Watch out for Python's recursion limit — with n up to 10,000 and a line-shaped tree, recursive DFS will stack-overflow; iterative BFS is safer.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach: Two-Sweep BFS with Parent Tracking
Core Idea
The algorithm makes exactly two BFS passes over the tree:
- Sweep 1 — BFS from any node (node
0works fine). The node farthest from the start, call itu, is an endpoint of some diameter. - Sweep 2 — BFS from
u, recording each node's parent pointer. The farthest node fromu, call itv, is the other endpoint, and the pathu → vis a diameter. - Reconstruction — Walk the parent pointers from
vback touto produce the path.
Why the Farthest Node from Any Start Is a Diameter Endpoint
This is the non-obvious piece interviewers probe. Here is a tight sketch:
Let a–b be a true diameter of length D, and let u be farthest from some arbitrary start s.
- If the
s→upath shares a nodexwith thea–bpath, thend(x, u) ≥ d(x, a)andd(x, u) ≥ d(x, b)(otherwiseuwould not be the farthest froms). Swapping whichever ofaorbis closer toxforuyields a path of length≥ D. SinceDis maximum,umust itself be a diameter endpoint. - If the two paths are disjoint, a similar exchange argument shows a path through
uwould be strictly longer thanDunless the lengths are tight — which forcesuto sit at a diameter endpoint.
Once u is confirmed as an endpoint, the farthest node from u completes the longest path by definition.
Why Not a Single DFS?
A single DFS rooted at an arbitrary node only considers paths that descend from that root to a leaf. A diameter can bend through any internal node. The single-DFS-DP approach (track the two deepest child subtrees at each node) correctly finds the length of the diameter, but recovering the actual path requires extra bookkeeping. The two-sweep BFS is simpler and equally efficient.
Complexity
- Time: O(n) — building the adjacency list is O(n), each BFS visits every node and edge once, and path reconstruction is O(n).
- Space: O(n) — adjacency list, distance and parent arrays, BFS queue.
Common Mistakes
- Recursive DFS with large input. A line-shaped tree with n = 10,000 nodes creates a recursion depth of 10,000, far above Python's default limit (~1,000). Always use iterative BFS here.
- Copying the path at every step. Storing a running path list at each node during DFS costs O(n²) overall. Parent-pointer reconstruction is O(n).
- Forgetting that any farthest node is valid. When multiple nodes tie for maximum distance, picking any of them is correct because the problem accepts any valid diameter path.
Python Solution
from collections import deque
from typing import List, Tuple
def longest_tree_path(n: int, edges: List[List[int]]) -> List[int]:
# Build undirected adjacency list.
adj: List[List[int]] = [[] for _ in range(n)]
for a, b in edges:
adj[a].append(b)
adj[b].append(a)
def bfs(start: int) -> Tuple[int, List[int]]:
"""BFS from `start`; return (farthest node, parent array)."""
dist = [-1] * n
parent = [-1] * n
dist[start] = 0
queue = deque([start])
farthest = start
while queue:
node = queue.popleft()
if dist[node] > dist[farthest]:
farthest = node
for neighbor in adj[node]:
if dist[neighbor] == -1:
dist[neighbor] = dist[node] + 1
parent[neighbor] = node
queue.append(neighbor)
return farthest, parent
# Sweep 1: find one diameter endpoint u.
u, _ = bfs(0)
# Sweep 2: find the other endpoint v; keep parents for reconstruction.
v, parent = bfs(u)
# Trace parent pointers from v back to u.
path: List[int] = []
node = v
while node != -1:
path.append(node)
node = parent[node]
return path # ordered v → u; reversing is fine if u → v order is preferred
Walkthrough on Example 2
edges = [[0,1],[1,2],[1,3]]
- BFS from
0: visits1(distance 1), then2and3(distance 2). First node dequeued at distance 2 is2, sou = 2. - BFS from
2: visits1(distance 1), then0and3(distance 2). First node at distance 2 is0, sov = 0. - Parent trace:
0 → 1 → 2. Result:[0, 1, 2]. ✓
Edge Cases
- Two nodes (
n = 2): Sweep 1 from0returnsu = 1. Sweep 2 from1returnsv = 0. Output:[0, 1]. - Star tree: Sweep 1 from the center returns any leaf. Sweep 2 from that leaf crosses the center to the farthest leaf. Output is
[leaf, center, leaf], length 2. - Line tree: output spans all
nnodes, whichever direction the parent trace goes.
Follow-ups Worth Knowing
Weighted edges (non-negative). The double-sweep still works. Accumulate edge weights instead of hop counts: dist[neighbor] = dist[node] + weight. No need for Dijkstra — there is exactly one path between any two nodes in a tree, so traversal order doesn't affect correctness. With negative weights, the farthest-node lemma breaks; switch to a tree DP that combines the two deepest non-negative child chains at each node.
Length only, no path needed. You can use a single DFS/DP pass: at each node, track the two largest depths into its subtrees; their sum is a candidate diameter. This halves traversal work but the asymptotic complexity is still O(n).