Need help in understanding solution to EXEPDIAM

In the solution to problem EXEPDIAM, we require the count of all possible endpoints of diameter of a tree. Moreover, if d is the diameter, we also require the count of all nodes whose farthest distance to any node in the tree is d-1.

My query is this: If f(u) = max_v(d(u, v)) where d(u, v), is the distance between u and v, how to effectively find f for all nodes in the tree?

PS: I have solved the original problem but I am unsure as to how/why it works.