KatInterview

Longest Path in an Undirected Tree

Trees & GraphsAuto-graded · 16 test cases
MediumAuto-gradedTrees & Graphsbfstreesgraph-traversal

Last 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_000
  • len(edges) == n - 1
  • 0 <= u, v < n and u != 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.