![]() |
VOOZH | about |
Given an undirected unweighted connected graph consisting of n vertices and m edges. The task is to find any spanning tree of this graph such that the maximum degree over all vertices is maximum possible. The order in which you print the output edges does not matter and an edge can be printed in reverse also i.e. (u, v) can also be printed as (v, u).
Examples:
Input: 1 / \ 2 5 \ / 3 | 4 Output: 3 2 3 5 3 4 1 2 The maximum degree over all vertices is of vertex 3 which is 3 and is maximum possible. Input: 1 / 2 / \ 5 3 | 4 Output: 2 1 2 5 2 3 3 4
Prerequisite: Kruskal Algorithm to find Minimum Spanning Tree
Approach: The given problem can be solved using Kruskal's algorithm to find the Minimum Spanning tree.
We find the vertex which has maximum degree in the graph. At first we will perform the union of all the edges which are incident to this vertex and then carry out normal Kruskal's algorithm. This gives us optimal spanning tree.
3 2 3 5 3 4 1 2
Time Complexity: O(N * logN), where N is the total number of nodes in the graph.
Auxiliary Space: O(N)