The Wayback Machine - https://web.archive.org/web/20240605051338/https://www.geeksforgeeks.org/check-if-a-tree-can-be-split-into-k-equal-connected-components/
Open In App

Check if a Tree can be split into K equal connected components

Last Updated : 28 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given Adjacency List representation of a tree and an integer K., the task is to find whether the given tree can be split into K equal Connected Components or not.
Note: Two connected components are said to be equal if they contain equal number of nodes.

Examples: 

Input: N = 15, K = 5 
Below is the given tree with Number nodes = 15 
 

Output: YES 
Explanation: 
Below is the 5 number of Connected Components can be made: 
 

Approach: 
The idea is to use Depth First Search(DFS) traversal on the given tree of N nodes to find whether the given tree can be split into K equal Connected Components or not. Following are the steps: 

  1. Start DFS Traversal with the root of the tree.
  2. For every vertex not visited during DFS traversal, recursively call DFS for that vertex keeping the count of nodes traverse during every DFS recursive call.
  3. If the count of nodes is equals to (N/K) then we got our one of the set of Connected Components.
  4. If the total number of the set of Connected Components of (N/K) nodes is equal to K. Then the given graph can be split into K equals Connected Components.

Below is the implementation of the above approach: 

C++




// C++ program to detect whether
// the given Tree can be split
// into K equals components
#include <bits/stdc++.h>
using namespace std;
 
// For checking if the graph
// can be split into K equal
// Connected Components
int flag = 0;
 
// DFS Traversal
int DFS(vector<int> adj[], int k,
        int i, int x)
{
 
    // Initialise ans to 1
    int ans = 1;
 
    // Traverse the adjacency
    // for vertex i
    for (auto& it : adj[i]) {
        if (it != k) {
            ans += DFS(adj, i, it, x);
        }
    }
 
    // If number of nodes is
    // greater than x, then
    // the tree cannot be split
    if (ans > x) {
        flag = 1;
        return 0;
    }
 
    // Check for requirement
    // of nodes
    else if (ans == x) {
        ans = 0;
    }
    return ans;
}
 
// A utility function to add
// an edge in an undirected
// Tree
void addEdge(vector<int> adj[],
             int u, int v)
{
    adj[u].push_back(v);
    adj[v].push_back(u);
}
 
// Driver's Code
int main()
{
    int N = 15, K = 5;
 
    // Adjacency List
    vector<int> adj[N + 1];
 
    // Adding edges to List
    addEdge(adj, 1, 2);
    addEdge(adj, 2, 3);
    addEdge(adj, 2, 4);
    addEdge(adj, 4, 5);
    addEdge(adj, 5, 6);
    addEdge(adj, 5, 7);
    addEdge(adj, 4, 8);
    addEdge(adj, 4, 9);
    addEdge(adj, 8, 11);
    addEdge(adj, 10, 11);
    addEdge(adj, 11, 14);
    addEdge(adj, 9, 12);
    addEdge(adj, 12, 15);
    addEdge(adj, 12, 13);
 
    // Check if tree can be split
    // into K Connected Components
    // of equal number of nodes
    if (N % K == 0) {
        // DFS call to Check
        // if tree can be split
        DFS(adj, -1, 1, N / K);
    }
 
    // If flag is 0, then the
    // given can be split to
    // Connected Components
    cout << (flag ? "NO" : "YES");
 
    return 0;
}


Java




// Java program to detect whether
// the given Tree can be split
// into K equals components
import java.util.*;
 
class GFG
{
  
// For checking if the graph
// can be split into K equal
// Connected Components
static int flag = 0;
  
// DFS Traversal
static int DFS(Vector<Integer> adj[], int k,
        int i, int x)
{
  
    // Initialise ans to 1
    int ans = 1;
  
    // Traverse the adjacency
    // for vertex i
    for (int it : adj[i]) {
        if (it != k) {
            ans += DFS(adj, i, it, x);
        }
    }
  
    // If number of nodes is
    // greater than x, then
    // the tree cannot be split
    if (ans > x) {
        flag = 1;
        return 0;
    }
  
    // Check for requirement
    // of nodes
    else if (ans == x) {
        ans = 0;
    }
    return ans;
}
  
// A utility function to add
// an edge in an undirected
// Tree
static void addEdge(Vector<Integer> adj[],
             int u, int v)
{
    adj[u].add(v);
    adj[v].add(u);
}
  
// Driver's Code
public static void main(String[] args)
{
    int N = 15, K = 5;
  
    // Adjacency List
    Vector<Integer> []adj = new Vector[N + 1];
    for(int i= 0; i < N + 1; i++)
        adj[i] = new Vector<Integer>();
     
    // Adding edges to List
    addEdge(adj, 1, 2);
    addEdge(adj, 2, 3);
    addEdge(adj, 2, 4);
    addEdge(adj, 4, 5);
    addEdge(adj, 5, 6);
    addEdge(adj, 5, 7);
    addEdge(adj, 4, 8);
    addEdge(adj, 4, 9);
    addEdge(adj, 8, 11);
    addEdge(adj, 10, 11);
    addEdge(adj, 11, 14);
    addEdge(adj, 9, 12);
    addEdge(adj, 12, 15);
    addEdge(adj, 12, 13);
  
    // Check if tree can be split
    // into K Connected Components
    // of equal number of nodes
    if (N % K == 0) {
        // DFS call to Check
        // if tree can be split
        DFS(adj, -1, 1, N / K);
    }
  
    // If flag is 0, then the
    // given can be split to
    // Connected Components
    System.out.print(flag==1 ? "NO" : "YES");
}
}
 
// This code is contributed by Rajput-Ji


Python3




# Python3 program to detect whether
# the given Tree can be split
# into K equals components
 
# For checking if the graph
# can be split into K equal
# Connected Components
flag = 0
 
# DFS Traversal
def DFS(adj, k, i, x):
     
    # Initialise ans to 1
    ans = 1
    
    # Traverse the adjacency
    # for vertex i
    for it in adj[i]:
        if it is not k:
            ans += DFS(adj, i, it, x)
             
    # If number of nodes is
    # greater than x, then
    # the tree cannot be split
    if (ans > x):
        flag = 1
        return 0
    
    # Check for requirement
    # of nodes
    elif (ans == x):
        ans = 0
     
    return ans
 
# A utility function to add
# an edge in an undirected
# Tree
def addEdge(adj, u, v):
     
    adj[u].append(v)
    adj[v].append(u)
 
# Driver code
if __name__=="__main__":
     
    (N, K) = (15, 5)
     
    # Adjacency List
    adj = [[] for i in range(N + 1)]
     
    # Adding edges to List
    addEdge(adj, 1, 2);
    addEdge(adj, 2, 3);
    addEdge(adj, 2, 4);
    addEdge(adj, 4, 5);
    addEdge(adj, 5, 6);
    addEdge(adj, 5, 7);
    addEdge(adj, 4, 8);
    addEdge(adj, 4, 9);
    addEdge(adj, 8, 11);
    addEdge(adj, 10, 11);
    addEdge(adj, 11, 14);
    addEdge(adj, 9, 12);
    addEdge(adj, 12, 15);
    addEdge(adj, 12, 13);
     
    # Check if tree can be split
    # into K Connected Components
    # of equal number of nodes
    if (N % K == 0):
         
        # DFS call to Check
        # if tree can be split
        DFS(adj, -1, 1, N // K)
    
    # If flag is 0, then the
    # given can be split to
    # Connected Components
    if flag == 1:
        print("NO")
    else:
        print("YES")
 
# This code is contributed by rutvik_56


C#




// C# program to detect whether
// the given Tree can be split
// into K equals components
using System;
using System.Collections.Generic;
 
class GFG
{
   
// For checking if the graph
// can be split into K equal
// Connected Components
static int flag = 0;
   
// DFS Traversal
static int DFS(List<int> []adj, int k,
        int i, int x)
{
   
    // Initialise ans to 1
    int ans = 1;
   
    // Traverse the adjacency
    // for vertex i
    foreach (int it in adj[i]) {
        if (it != k) {
            ans += DFS(adj, i, it, x);
        }
    }
   
    // If number of nodes is
    // greater than x, then
    // the tree cannot be split
    if (ans > x) {
        flag = 1;
        return 0;
    }
   
    // Check for requirement
    // of nodes
    else if (ans == x) {
        ans = 0;
    }
    return ans;
}
   
// A utility function to add
// an edge in an undirected
// Tree
static void addEdge(List<int> []adj,
             int u, int v)
{
    adj[u].Add(v);
    adj[v].Add(u);
}
   
// Driver's Code
public static void Main(String[] args)
{
    int N = 15, K = 5;
   
    // Adjacency List
    List<int> []adj = new List<int>[N + 1];
    for(int i= 0; i < N + 1; i++)
        adj[i] = new List<int>();
      
    // Adding edges to List
    addEdge(adj, 1, 2);
    addEdge(adj, 2, 3);
    addEdge(adj, 2, 4);
    addEdge(adj, 4, 5);
    addEdge(adj, 5, 6);
    addEdge(adj, 5, 7);
    addEdge(adj, 4, 8);
    addEdge(adj, 4, 9);
    addEdge(adj, 8, 11);
    addEdge(adj, 10, 11);
    addEdge(adj, 11, 14);
    addEdge(adj, 9, 12);
    addEdge(adj, 12, 15);
    addEdge(adj, 12, 13);
   
    // Check if tree can be split
    // into K Connected Components
    // of equal number of nodes
    if (N % K == 0) {
        // DFS call to Check
        // if tree can be split
        DFS(adj, -1, 1, N / K);
    }
   
    // If flag is 0, then the
    // given can be split to
    // Connected Components
    Console.Write(flag==1 ? "NO" : "YES");
}
}
 
// This code contributed by Rajput-Ji


Javascript




<script>
  
 
// Javascript program to detect whether
// the given Tree can be split
// into K equals components
 
// For checking if the graph
// can be split into K equal
// Connected Components
var flag = 0;
 
// DFS Traversal
function DFS(adj, k, i, x)
{
 
    // Initialise ans to 1
    var ans = 1;
 
    // Traverse the adjacency
    // for vertex i
    adj[i].forEach(element => {
        if (element != k) {
            ans += DFS(adj, i, element, x);
        }
    });
 
    // If number of nodes is
    // greater than x, then
    // the tree cannot be split
    if (ans > x) {
        flag = 1;
        return 0;
    }
 
    // Check for requirement
    // of nodes
    else if (ans == x) {
        ans = 0;
    }
    return ans;
}
 
// A utility function to add
// an edge in an undirected
// Tree
function addEdge(adj, u, v)
{
    adj[u].push(v);
    adj[v].push(u);
}
 
// Driver's Code
var N = 15, K = 5;
// Adjacency List
var adj = Array.from(Array(N+1), ()=> Array());
// Adding edges to List
addEdge(adj, 1, 2);
addEdge(adj, 2, 3);
addEdge(adj, 2, 4);
addEdge(adj, 4, 5);
addEdge(adj, 5, 6);
addEdge(adj, 5, 7);
addEdge(adj, 4, 8);
addEdge(adj, 4, 9);
addEdge(adj, 8, 11);
addEdge(adj, 10, 11);
addEdge(adj, 11, 14);
addEdge(adj, 9, 12);
addEdge(adj, 12, 15);
addEdge(adj, 12, 13);
// Check if tree can be split
// into K Connected Components
// of equal number of nodes
if (N % K == 0) {
    // DFS call to Check
    // if tree can be split
    DFS(adj, -1, 1, N / K);
}
// If flag is 0, then the
// given can be split to
// Connected Components
document.write(flag ? "NO" : "YES");
 
 
</script>


Output: 

YES

 

Time Complexity: O(V + E), where V is the number of vertices and E is the number of edges
Auxiliary Space: O(V) due to recursion stack space. Ignoring the space used by the adjacency list as it is given.
 



Similar Reads

Minimum length of a rod that can be split into N equal parts that can further be split into given number of equal parts
Given an array arr[] consisting of N positive integers, the task is to find the minimum possible length of a rod that can be cut into N equal parts such that every ith part can be cut into arr[i] equal parts. Examples: Input: arr[] = {1, 2}Output: 4Explanation:Consider the length of the rod as 4. Then it can be divided in 2 equal parts, each having
7 min read
Check if an array can be split into 3 subsequences of equal sum or not
Given an array arr[] having N integers. The task is to determine if the array can be partitioned into 3 subsequences of an equal sum or not. If yes then print “Yes”. Otherwise, print “No”. Examples: Input: arr[] = {1, 1, 1}Output: YesExplanation:Here array can be partition into 3 equal sum. {1} Input: arr[] = {40}Output: NoExplanation:Here array ca
16 min read
Check if an array can be split into K non-overlapping subarrays whose Bitwise AND values are equal
Given an array arr[] of size N and a positive integer K, the task is to check if the array can be split into K non-overlapping and non-empty subarrays such that Bitwise AND of all the subarrays are equal. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: arr[] = { 3, 2, 2, 6, 2 }, K = 3 Output: YES Explanation: Splittin
11 min read
Check if a Binary String can be split into disjoint subsequences which are equal to "010"
Given a binary string, S of size N, the task is to check if it is possible to partition the string into disjoint subsequences equal to "010". Examples: Input: S = "010100"Output: YesExplanation: Partitioning the string in the manner 010100 to generate two subsequences equal to "010". Input: S = "010000"Output: No Approach: The idea is based on the
8 min read
Check if a numeric string can be split into substrings having difference between consecutive numbers equal to K
Given a numeric string S consisting of N digits and a positive integer K, the task is to check if the given string can be split into more than one substrings with difference between consecutive substrings equal to K. Examples: Input: S = "8642", K = 2Output: YesExplanation: Split the given string as {"8", "6", "4", "2"}. Now, the difference between
6 min read
Check if a string can be split into two substrings with equal number of vowels
Given a string S, the task is to check if the string can be split into two substrings such that the number of vowels in both of them are equal. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: S = "geeks"Output: YesExplanation: Splitting the strings into substrings "ge" (count of vowels = 1) and "eks" (count of vowels
17 min read
Queries to count connected components after removal of a vertex from a Tree
Given a Tree consisting of N nodes valued in the range [0, N) and an array Queries[] of Q integers consisting of values in the range [0, N). The task for each query is to remove the vertex valued Q[i] and count the connected components in the resulting graph. Examples: Input: N = 7, Edges[][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6}}, Que
8 min read
Convert undirected connected graph to strongly connected directed graph
Given an undirected graph of N vertices and M edges, the task is to assign directions to the given M Edges such that the graph becomes Strongly Connected Components. If a graph cannot be converted into Strongly Connected Components then print "-1". Examples: Input: N = 5, Edges[][] = { { 0, 1 }, { 0, 2 }, { 1, 2 }, { 1, 4 }, { 2, 3 }, { 3, 4 } } Ou
14 min read
Check if the length of all connected components is a Fibonacci number
Given an undirected graph with V vertices and E edges, the task is to find all the connected components of the graph and check if each of their lengths are a Fibonacci number or not. For example, consider the following graph. As depicted above, the lengths of the connected components are 2, 3, and 2 which are Fibonacci numbers. Examples: Input: E =
18 min read
Split an Array A[] into Subsets having equal Sum and sizes equal to elements of Array B[]
Given an array A[] consisting of N integers, the task is to split the array A[] into subsets having equal sum and of length equal to elements in array B[]. Examples: Input: A[] = {17, 13, 21, 20, 50, 29}, B[] = {2, 3, 1} Output: 21 29 17 13 20 50 Input: A[] = { 1, 2, 3, 4, 5, 6}, B[] = { 2, 2, 2} Output: 1 6 2 5 3 4 Approach: Follow the steps below
8 min read