Finding Center of The Tree

前端 未结 3 1862
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-16 02:52

I have a question which is part of my program.

For a tree T=(V,E) we need to find the node v in the tree that minimize the length of the longest path from v to any o

3条回答
  •  -上瘾入骨i
    2020-12-16 03:09

    There are two approaches to do this (both runs in the same time):

    • using BFS (which I will describe here)
    • using FIFO queue.

    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.

提交回复
热议问题