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 time and uses space.