Question Details

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

Show Answer

Correct Answer :

6

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
v
and find the farthest vertex
u
from
v
using BFS.

2. Second BFS: Start a new BFS from
u
and find the farthest vertex
z
from
u
using BFS.

3. Output: The shortest path distance between
u
and
z
which corresponds to the diameter of the tree.

Why the Algorithm Works on a Tree
For any tree
T
this algorithm is guaranteed to find the correct diameter because of the following property:
- The node
u
found during the first BFS starting from any arbitrary node
v
is guaranteed to be one of the endpoints of a longest path (diameter) of the tree.
- The subsequent BFS starting from the endpoint
u
will traverse to the other endpoint
z
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.

Unlock Our Free Library

Access expert-curated educational resources and study materials—completely free.

Ask AI Tutor
5 left
Q1 View Question & Options
AI Tutor is solving this question...
Reading question context & options...