~/problems / Trees / Tree DP

Basics: Diameter of a tree

easy basics ~10 min

A tree has nodes 0 .. n-1 and is given as a list of n - 1 undirected edges (u, v). Its diameter is the number of edges on the longest simple path between any two nodes.

Implement tree_diameter(n: int, edges: list[tuple[int, int]]) -> int.

tree_diameter(5, [(0, 1), (1, 2), (1, 3), (3, 4)])  # 3   path 2-1-3-4 (or 0-1-3-4)
tree_diameter(1, [])                                # 0   a lone node

Constraints: 1 <= n <= 500, and the edges always form one connected tree. Recursion is fine at this size. Running a BFS from every node works but misses the point: do it with one depth-first traversal.

Show hint

root the tree anywhere; each node returns its longest downward path to its parent, but records as a candidate answer the path that bends through it, which is its two longest child paths added together.

Topic: Tree DP. Post-order: each node returns a small tuple of states to its parent.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc