Graph Theory37 sections · 1633 units
Open in Course

CSES 1131 Tree Diameter - Problem Statement

CSES 1131

You are given a tree with nn nodes. Find the diameter: the maximum distance between any two nodes. Input: First line has nn. Next n1n-1 lines each have two integers aa and bb representing an edge. Output: Single integer, the diameter. Constraints: 1n2×1051 \leq n \leq 2 \times 10^5 This is the classic tree diameter problem.

Solve it efficiently using two-BFS or DP. Both approaches run in O(n)O(n) time and teach you core techniques for tree problems.

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