progress

~/problems / Trees / Tree DP

Height of a tree

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

easy basics ~10 min

A tree has nodes 0 .. n-1 and is given as a list of n - 1 undirected edges (u, v). Hang it from node 0, so 0 is the root. Its height is the number of edges on the longest path from the root down to any node.

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

tree_height(5, [(0, 1), (1, 2), (1, 3), (3, 4)])  # 3   path 0-1-3-4
The tree hung from node 0: 0 above 1, 1 above 2 and 3, and 3 above 4, each node labelled with its height; the longest downward path 0, 1, 3, 4 has 3 edges
tree_height(4, [(0, 1), (0, 2), (0, 3)])          # 1   every other node hangs right off 0
tree_height(1, [])                                # 0   a lone node

Constraints: 1 <= n <= 500, and the edges always form one connected tree. Recursion is fine at this size.

Show hint

a leaf has height 0; any other node has height 1 + the largest height among its children. The edges go both ways, so pass each call its parent and don't walk back up.

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