VOOZH about

URL: https://www.geeksforgeeks.org/dsa/optimal-tree-connectivity/

⇱ Optimal Tree Connectivity - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Optimal Tree Connectivity

Last Updated : 15 Jan, 2024

Given an undirected tree consisting of n vertices and n-1 edges. The task is to add the minimum number of edges in such a way that the length of the shortest path from vertex 1 to any other vertex is at most 2. The edges should be added in a way that the graph does not contain any loops.

Example:

Input: n = 7, edges = {{1, 2}, {2, 3}, {2, 4}, {4, 5}, {4, 6}, {5, 7}}
Output: 2

Input: n = 7, edges = {{1, 2}, {1, 3}, {2, 4}, {2, 5}, {3, 6}, {1, 7}}
Output: 0

Approach:

The idea is to perform a Depth-First Search (DFS) on an undirected tree to calculate the distance of each vertex from the root. It then identifies vertices whose distance from the root exceeds 2 and removes them along with their neighbors iteratively until the resulting graph satisfies the condition of having a minimum shortest path of at most 2 from vertex 1 to any other vertex. The count of removed vertices and their neighbors represents the minimum number of edges to be added to meet the given criteria.

Step-by-step approach:

  • DFS to Calculate Distances:
    • Perform a Depth-First Search (DFS) on the tree to calculate the distance of each vertex from the root (vertex 1).
    • Store the parent of each vertex and the distance from the root.
  • Identify Vertices to Remove:
    • Identify vertices whose distance from the root is greater than 2.
    • Use a set to store these vertices along with their distances.
  • Remove Vertices Iteratively:
    • While there are vertices to remove:
      • Remove a vertex and its corresponding distance from the set.
      • Remove the same vertex and its neighbors from the set.
      • Increment the answer count.
  • Print the count of removed vertices, which represents the minimum number of edges to add.

Below is the implementation of the above approach:


Output
2

Time Complexity: O(n log n)
Auxiliary Space: O(n).

Comment