Question
Consider the following algorithm someAlgo that takes an undirected graph as input.
someAlgo(G)
1. 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.
2. 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.
3. Output the distance between u and z in G.
The output of someAlgo(T) for the tree shown in the given figure is ___________. (Answer in integer)
Official answer and solution
- Official answer
- 6
- From
- Official GATE 2025 answer key
Solution
Recognize that two-pass BFS on a tree always outputs the diameter (number of edges on the longest simple path) of the tree.
For any tree , running BFS from an arbitrary vertex to find a farthest vertex , and then running BFS from to find a farthest vertex , is the standard two-BFS algorithm that computes the diameter of (the maximum distance in edges between any two vertices in ).
In the given tree , the longest path goes from the bottom-left leaf (or either of the two top-left leaves at distance 2 from the left degree-4 hub) through the 5 internal nodes on the main backbone to the rightmost leaf, spanning edges.
6
Counting the number of vertices (7) on the longest path instead of the number of edges (6).
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2025 Computer Science and Information Technology - Session 2 (CS2)
- Question
- 59 of 65
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.