centre node in a tree

前端 未结 2 1891
时光取名叫无心
时光取名叫无心 2020-12-03 00:17

Given a tree, how to find the centre node in the tree so that the distance from the central node to other nodes is minimum(assuming each edge has unit weight)? I am trying t

2条回答
  •  再見小時候
    2020-12-03 00:33

    Here is another approach that also runs in O(V).

    Select any vertex v1 on your tree. Run BFS from this vertex. The last vertex (v2) you will proceed will be the furthest vertex from v1. Now run another BFS, this time from vertex v2 and get the last vertex v3.

    The path from v2 to v3 is the diameter of the tree and your center lies somewhere on it. More precisely it lies in the middle of it. If the path has 2n + 1 points, there will be only 1 center (in the position n + 1). If the path has 2n points, there will be two centers at the positions n and n + 1.

    You only use 2 BFS calls which runs in 2 * O(V) time.

提交回复
热议问题