~/problems / Trees / Tree DP

Tree Diameter

easy ~15 min

Implement tree_diameter(n, edges) -> int.

The tree has n nodes numbered 1..n and n - 1 undirected edges, each a pair (a, b). It isn't binary and has no root. Return its diameter: the largest number of edges on the path between any two nodes. A single node has diameter 0.

tree_diameter(5, [(1, 2), (1, 3), (3, 4), (3, 5)])
# 3   (for example 2 -> 1 -> 3 -> 4)

n goes up to 100,000, and the tree may be one long path, so recursion will hit Python's limit. Aim for O(n): a search from every node is O(n²) and too slow.

Show hint

Start from any node and find the node farthest from it. Where does the longest path in the whole tree have to end?

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