Graph Theory37 sections · 1633 units
Open in Course

CSES 1131 Tree Diameter - Walkthrough

Example trace

Example tree: edges (11,22), (11,33), (33,44), (33,55).

First BFS from node 11: distances are {11:00, 22:11, 33:11, 44:22, 55:22}. Farthest nodes are 44 and 55 (distance 22). Pick u=4u = 4.

Second BFS from node 44: distances are {44:00, 33:11, 11:22, 55:22, 22:33}. Farthest node is 22 (distance 33). The diameter is 33: the path 44-33-11-22.

Notice how starting from an arbitrary node (11) found an endpoint (44), and BFS from there found the true diameter.