Question:

Consider the following algorithm tt{someAlgo that takes an undirected graph \( G \) as input.} tt{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 \( u \) as given by the BFS. Output the distance between \( u \) and \( z \) in \( G \). The output of tt{someAlgo(T)} for the tree shown in the given figure is ___________ . (Answer in integer) \begin{center} \includegraphics{q59_fig.png} \end{center}

Show Hint

To find the diameter of a tree, use two BFS traversals: first to find the farthest node from any starting node, and second to determine the farthest node from the previously found node.
Updated On: Jan 30, 2026
Hide Solution
collegedunia
Verified By Collegedunia

Correct Answer: 6

Solution and Explanation

The algorithm tt{someAlgo} effectively finds the diameter of the tree \( T \), which is the longest shortest path between any two nodes in the tree. Step 1: Run BFS from any arbitrary node \( v \) - Select an arbitrary node and perform a BFS to find the farthest node \( u \). Step 2: Run BFS from \( u \) to find the farthest node \( z \) - Perform another BFS starting from \( u \) to determine the farthest node \( z \). Step 3: Compute the distance between \( u \) and \( z \) - The distance obtained in this second BFS represents the tree's diameter. From the given tree diagram, the longest shortest path (diameter) is found to be \( 6 \).
Was this answer helpful?
0
0

Top Questions on Trees

View More Questions