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)
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.