Graph Theory37 sections · 1633 units
Open in Course

CSES 1132 Tree Distances I - Algorithm

Three BFS approach

1.1. Run BFS from node 11 to find one diameter endpoint uu.

2.2. Run BFS from uu to find the other endpoint vv.

3.3. Run BFS from vv (or reuse from step 22).

4.4. For each node xx: answer = max(dist from uu, dist from vv).

Three BFS calls total: O(n)O(n). This exploits the fact that diameter endpoints are the "extreme" nodes. Any other node's farthest point must be one of them.

Space complexity is O(n)O(n) for the data structures used.