Graph Theory37 sections · 1633 units
Open in Course

CSES 1132 Tree Distances I - Implementation

Pseudocode

Here is the solution:

read n
adj = array of n + 1 empty lists
for i from 1 to n - 1:
    read a, b
    adj[a].append(b)
    adj[b].append(a)

dist1 = bfs(1, adj, n)
u = node with maximum dist1

distU = bfs(u, adj, n)
v = node with maximum distU

distV = bfs(v, adj, n)

for i from 1 to n:
    print max(distU[i], distV[i])

This runs in O(n)O(n) time and uses O(n)O(n) space.