Graph Theory37 sections · 1633 units
Open in Course

Problem - Tree Diameter

(CSES - Longest path)

Subordinates was a warm-up: one DFS, count subtree sizes. Now let's solve a classic problem that requires more thought.

Given a tree of n nodes, find the diameter: the longest path between any two nodes. Unlike Subordinates, we're not computing something for each node's subtree. We need a global answer.

Before looking at the solution, think: Can you solve this with a single DFS? Or do you need something more?