If the "center" of a tree is defined as the "node of the graph that minimizes the depth of the tree", there is an easier way to find it than to find the diameter.
d[] = degrees of all nodes que = { leaves, ie i that d[i]==1} while len(que) > 1: i=que.pop_front d[i]-- for j in neighbors[i]: if d[j] > 0: d[j]-- if d[j] == 1 : que.push_back(j)
and the last remaining in que is the center.
you can prove it by thinking about the diameter path. for simplicity, we assume that the length of the diameter path is odd, so that the middle node of the path is unique, let's say that node M,
we can see that:
- M will not be placed at the end of the queue until all node else on the diameter path has been placed in que
- if there is still a node N that is pushed out after M has already been placed in the que, then N should be on a longer path than the diameter path. Therefore, N cannot exist. M should be the last node pressed (and left) in que
source share