Graph Theory37 sections · 1633 units
Open in Course

CSES 1132 Tree Distances I - Problem Statement

CSES 1132

You are given a tree with nn nodes. For each node, calculate the maximum distance from that node to any other node. This extends diameter to all nodes. Naive approach: run BFS from every node, O(n2)O(n^2).

Better approach: use the diameter endpoints. For any node vv, its farthest node is one of the diameter endpoints. Run BFS from both endpoints, then answer for each node is max of the two distances.

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