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
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.