Graph Theory37 sections · 1633 units
Open in Course

CSES 1131 Tree Diameter - Double BFS Algorithm

Pick node, find furthest, repeat

Double BFS finds the diameter in 22 passes:

1.1. BFS from any node. Find the farthest node AA.

2.2. BFS from AA. Find the farthest node BB.

The distance from AA to BB is the diameter. You do not need to try every starting node. The first BFS always lands on a diameter endpoint, no matter where you start. This runs in O(n)O(n) time and uses O(n)O(n) space. The Tree Diameter & Center section proves why this property holds and walks through a full example with code.