Since this is a tree, there is only one path between any pair of vertices. This makes it easy for us to find the diameter of the graph.
The easiest way to do this is to do two simple tree walks. First, take any arbitrary node as the root and calculate the distance from each vertex from it using simple DFS / BFS. Now take the node that is farthest from the root (this is the first node of the most remote pair), and making it the new root, start another traversal of the trees calculating the distances from there. The farthest node from this is another node of the pair.
The proof of why this works remains as an exercise.
There is also another way to calculate the most remote pair by calculating and comparing the most remote pairs for each subtree of the tree, starting with an arbitrary node as the root (already mentioned in another answer).
MAK
source share