Graph Theory37 sections · 1633 units
Open in Course

The Naive Approach

Try all pairs

You could run BFS from every node, find the farthest distance from each, and take the maximum. That gives you the diameter but costs O(n2)O(n^2) time: O(n)O(n) BFS calls, each taking O(n)O(n).

For small trees this works. For n=105n = 10^5, you would do 101010^{10} operations, which is too slow. You need a smarter approach that finds the diameter without checking every starting point. The two-BFS method does exactly this in O(n)O(n) total time. It exploits a property of trees that general graphs lack.

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