Consider the following algorithm someAlgo that takes an undirected graph G as input.
someAlgo (G)
Let v be any vertex in G. Run BFS on G starting at v. Let u be a vertex in G at maximum distance from v as given by the BFS.
Run BFS on G again with u as the starting vertex. Let z be the vertex at maximum distance from uu as given by the BFS.
Output the distance between u and z in G.
The output of someAlgo(T) for the tree shown in the given figure is ______.
Correct Answer :
Solution :
The correct answer is 6.
Understanding the Algorithm
The given algorithm, someAlgo(G), is a well-known, efficient two-pass Breadth-First Search (BFS) algorithm used to find the diameter of a tree. The diameter of a tree is defined as the length of the longest path (in terms of the number of edges) between any two vertices in the tree.
Let's break down the steps of the algorithm:
1. First BFS: Start at an arbitrary vertex
and find the farthest vertex
from
using BFS.
2. Second BFS: Start a new BFS from
and find the farthest vertex
from
using BFS.
3. Output: The shortest path distance between
and
which corresponds to the diameter of the tree.
Why the Algorithm Works on a Tree
For any tree
this algorithm is guaranteed to find the correct diameter because of the following property:
- The node
found during the first BFS starting from any arbitrary node
is guaranteed to be one of the endpoints of a longest path (diameter) of the tree.
- The subsequent BFS starting from the endpoint
will traverse to the other endpoint
of the diameter path.
Since the correct answer is 6, the diameter of the tree shown in the figure is 6, meaning the longest path between any two nodes in the tree consists of exactly 6 edges.
Access expert-curated educational resources and study materials—completely free.
Create, conduct, and manage professional online assessments with Mindyard. Perfect for teachers and institutes.
Copyright © 2026 Mindyard. All Rights Reserved.