Linear algorithm of finding tree diameter

前端 未结 2 1647
一向
一向 2021-02-06 13:04

I have the following code to find the diameter of a tree:

ALGORITHM: TREE_DIAMETER (T)

maxlength ← 0
for s ← 0 to s < |V[T]|
      do temp ← BSF(T, S)
               


        
2条回答
  •  悲哀的现实
    2021-02-06 13:37

    Here is a simple algorithm with linear time complexity:
    1)Pick an arbitrary vertex v.
    2)Find the furthest vertex from v using BFS(let's call it u).
    3)Find the furthest vertex from u using BFS one more time(let's call it t).
    Then distance(u, t) is the diameter.
    BFS is called only twice, so the time complexity is linear.

提交回复
热议问题