KatInterview

Find the Longest Path in an Undirected Tree

Trees & GraphsModel answer
MediumModel answerTrees & GraphsBFSDFStree diameter

Last 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,000
  • edges has exactly n-1 entries 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.