progress

~/problems / Trees / Tree DP

Tree Diameter

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~20 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)
A five-node tree with edges 1-2, 1-3, 3-4 and 3-5; the longest path, 2 to 1 to 3 to 4, has 3 edges

n goes up to 100,000.

⭐ Bonus: a speed test with 100,000-node trees (one is a long path, too deep for recursion) earns a star in O(n). A search from every node is O(n²).

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