Open In App

Convert a tree to forest of even nodes

Last Updated : 20 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a tree of n even nodes. The task is to find the maximum number of edges to be removed from the given tree to obtain forest of trees having even number of nodes. This problem is always solvable as given graph has even nodes.

Examples: 

Input : n = 10
Edge 1: 1 3
Edge 2: 1 6
Edge 3: 1 2
Edge 4: 3 4
Edge 5: 6 8
Edge 6: 2 7
Edge 7: 2 5
Edge 8: 4 9
Edge 9: 4 10

Output : 2

By removing 2 edges we can obtain the forest with even node tree.

Dotted line shows removed edges. Any further removal of edge will not satisfy 
the even nodes condition.

Find a subtree with even number of nodes and remove it from rest of tree by removing the edge connecting it. After removal, we are left with tree with even node only because initially we have even number of nodes in the tree and removed subtree has also even node. Repeat the same procedure until we left with the tree that cannot be further decomposed in this manner.

To do this, the idea is to use Depth First Search to traverse the tree. Implement DFS function in such a manner that it will return number of nodes in the subtree whose root is node on which DFS is performed. If the number of nodes is even then remove the edge, else ignore.

Below is implementation of this approach: 

C++




// C++ program to find maximum number to be removed
// to convert a tree into forest containing trees of
// even number of nodes
#include<bits/stdc++.h>
#define N 12
using namespace std;
 
// Return the number of nodes of subtree having
// node as a root.
int dfs(vector<int> tree[N], int visit[N],
                      int *ans, int node)
{
    int num = 0, temp = 0;
 
    // Mark node as visited.
    visit[node] = 1;
 
    // Traverse the adjacency list to find non-
    // visited node.
    for (int i = 0; i < tree[node].size(); i++)
    {
        if (visit[tree[node][i]] == 0)
        {
            // Finding number of nodes of the subtree
            // of a subtree.
            temp = dfs(tree, visit, ans, tree[node][i]);
 
            // If nodes are even, increment number of
            // edges to removed.
            // Else leave the node as child of subtree.
            (temp%2)?(num += temp):((*ans)++);
        }
    }
 
    return num+1;
}
 
// Return the maximum number of edge to remove
// to make forest.
int minEdge(vector<int> tree[N], int n)
{
    int visit[n+2];
    int ans = 0;
    memset(visit, 0, sizeof visit);
 
    dfs(tree, visit, &ans, 1);
 
    return ans;
}
 
// Driven Program
int main()
{
    int n = 10;
 
    vector<int> tree[n+2];
    tree[1].push_back(3);
    tree[3].push_back(1);
 
    tree[1].push_back(6);
    tree[6].push_back(1);
 
    tree[1].push_back(2);
    tree[2].push_back(1);
 
    tree[3].push_back(4);
    tree[4].push_back(3);
 
    tree[6].push_back(8);
    tree[8].push_back(6);
 
    tree[2].push_back(7);
    tree[7].push_back(2);
 
    tree[2].push_back(5);
    tree[5].push_back(2);
 
    tree[4].push_back(9);
    tree[9].push_back(4);
 
    tree[4].push_back(10);
    tree[10].push_back(4);
 
    cout << minEdge(tree, n) << endl;
    return 0;
}


Java




// Java program to find maximum number to be removed
// to convert a tree into forest containing trees of
// even number of nodes
import java.util.*;
 
class GFG
{
    static int N = 12,ans;
     
    static Vector<Vector<Integer>> tree=new Vector<Vector<Integer>>();
     
    // Return the number of nodes of subtree having
    // node as a root.
    static int dfs( int visit[], int node)
    {
        int num = 0, temp = 0;
     
        // Mark node as visited.
        visit[node] = 1;
     
        // Traverse the adjacency list to find non-
        // visited node.
        for (int i = 0; i < tree.get(node).size(); i++)
        {
            if (visit[tree.get(node).get(i)] == 0)
            {
                // Finding number of nodes of the subtree
                // of a subtree.
                temp = dfs( visit, tree.get(node).get(i));
     
                // If nodes are even, increment number of
                // edges to removed.
                // Else leave the node as child of subtree.
                if(temp%2!=0)
                num += temp;
                else
                ans++;
            }
        }
     
        return num+1;
    }
     
    // Return the maximum number of edge to remove
    // to make forest.
    static int minEdge( int n)
    {
        int visit[] = new int[n+2];
        ans = 0;
     
        dfs( visit, 1);
     
        return ans;
    }
     
    // Driven Program
    public static void main(String args[])
    {
        int n = 10;
         
        //set the size of vector
        for(int i = 0; i < n + 2;i++)
        tree.add(new Vector<Integer>());
     
        tree.get(1).add(3);
        tree.get(3).add(1);
     
        tree.get(1).add(6);
        tree.get(6).add(1);
     
        tree.get(1).add(2);
        tree.get(2).add(1);
     
        tree.get(3).add(4);
        tree.get(4).add(3);
     
        tree.get(6).add(8);
        tree.get(8).add(6);
     
        tree.get(2).add(7);
        tree.get(7).add(2);
     
        tree.get(2).add(5);
        tree.get(5).add(2);
     
        tree.get(4).add(9);
        tree.get(9).add(4);
     
        tree.get(4).add(10);
        tree.get(10).add(4);
     
        System.out.println( minEdge( n));
    }
}
 
// This code is contributed by Arnab Kundu


Python3




# Python3 program to find maximum
# number to be removed to convert
# a tree into forest containing trees
# of even number of nodes
 
# Return the number of nodes of 
# subtree having node as a root.
def dfs(tree, visit, ans, node):
    num = 0
    temp = 0
 
    # Mark node as visited.
    visit[node] = 1
 
    # Traverse the adjacency list 
    # to find non-visited node.
    for i in range(len(tree[node])):
        if (visit[tree[node][i]] == 0):
             
            # Finding number of nodes of
            # the subtree of a subtree.
            temp = dfs(tree, visit, ans,
                          tree[node][i])
 
            # If nodes are even, increment
            # number of edges to removed.
            # Else leave the node as child
            # of subtree.
            if(temp % 2):
                num += temp
            else:
                ans[0] += 1
 
    return num + 1
 
# Return the maximum number of
# edge to remove to make forest.
def minEdge(tree, n):
    visit = [0] * (n + 2)
    ans = [0]
    dfs(tree, visit, ans, 1)
 
    return ans[0]
 
# Driver Code
N = 12
n = 10
 
tree = [[] for i in range(n + 2)]
tree[1].append(3)
tree[3].append(1)
 
tree[1].append(6)
tree[6].append(1)
 
tree[1].append(2)
tree[2].append(1)
 
tree[3].append(4)
tree[4].append(3)
 
tree[6].append(8)
tree[8].append(6)
 
tree[2].append(7)
tree[7].append(2)
 
tree[2].append(5)
tree[5].append(2)
 
tree[4].append(9)
tree[9].append(4)
 
tree[4].append(10)
tree[10].append(4)
 
print(minEdge(tree, n))
 
# This code is contributed by pranchalK


C#




// C# program to find maximum number
// to be removed to convert a tree into
// forest containing trees of even number of nodes
using System;
using System.Collections.Generic;
 
class GFG
{
    static int N = 12, ans;
     
    static List<List<int>> tree = new List<List<int>>();
     
    // Return the number of nodes of
    // subtree having node as a root.
    static int dfs(int []visit, int node)
    {
        int num = 0, temp = 0;
     
        // Mark node as visited.
        visit[node] = 1;
     
        // Traverse the adjacency list to
        // find non-visited node.
        for (int i = 0; i < tree[node].Count; i++)
        {
            if (visit[tree[node][i]] == 0)
            {
                // Finding number of nodes of the
                // subtree of a subtree.
                temp = dfs(visit, tree[node][i]);
     
                // If nodes are even, increment number of
                // edges to removed.
                // Else leave the node as child of subtree.
                if(temp % 2 != 0)
                    num += temp;
                else
                    ans++;
            }
        }
        return num + 1;
    }
     
    // Return the maximum number of edge
    // to remove to make forest.
    static int minEdge(int n)
    {
        int []visit = new int[n + 2];
        ans = 0;
     
        dfs(visit, 1);
     
        return ans;
    }
     
    // Driver Code
    public static void Main(String []args)
    {
        int n = 10;
         
        //set the size of vector
        for(int i = 0; i < n + 2;i++)
        tree.Add(new List<int>());
     
        tree[1].Add(3);
        tree[3].Add(1);
     
        tree[1].Add(6);
        tree[6].Add(1);
     
        tree[1].Add(2);
        tree[2].Add(1);
     
        tree[3].Add(4);
        tree[4].Add(3);
     
        tree[6].Add(8);
        tree[8].Add(6);
     
        tree[2].Add(7);
        tree[7].Add(2);
     
        tree[2].Add(5);
        tree[5].Add(2);
     
        tree[4].Add(9);
        tree[9].Add(4);
     
        tree[4].Add(10);
        tree[10].Add(4);
     
        Console.WriteLine(minEdge(n));
    }
}
 
// This code is contributed by Rajput-Ji


Javascript




<script>
 
// JavaScript program to find maximum number
// to be removed to convert a tree into
// forest containing trees of even number of nodes
var N = 12, ans;
 
var tree = Array();
 
// Return the number of nodes of
// subtree having node as a root.
function dfs(visit, node)
{
    var num = 0, temp = 0;
 
    // Mark node as visited.
    visit[node] = 1;
 
    // Traverse the adjacency list to
    // find non-visited node.
    for (var i = 0; i < tree[node].length; i++)
    {
        if (visit[tree[node][i]] == 0)
        {
            // Finding number of nodes of the
            // subtree of a subtree.
            temp = dfs(visit, tree[node][i]);
 
            // If nodes are even, increment number of
            // edges to removed.
            // Else leave the node as child of subtree.
            if(temp % 2 != 0)
                num += temp;
            else
                ans++;
        }
    }
    return num + 1;
}
 
// Return the maximum number of edge
// to remove to make forest.
function minEdge(n)
{
    var visit = Array(n+2).fill(0);
    ans = 0;
 
    dfs(visit, 1);
 
    return ans;
}
 
// Driver Code
var n = 10;
 
//set the size of vector
for(var i = 0; i < n + 2;i++)
    tree.push(new Array());
tree[1].push(3);
tree[3].push(1);
tree[1].push(6);
tree[6].push(1);
tree[1].push(2);
tree[2].push(1);
tree[3].push(4);
tree[4].push(3);
tree[6].push(8);
tree[8].push(6);
tree[2].push(7);
tree[7].push(2);
tree[2].push(5);
tree[5].push(2);
tree[4].push(9);
tree[9].push(4);
tree[4].push(10);
tree[10].push(4);
document.write(minEdge(n));
 
 
</script>


Output

2

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

 



Previous Article
Next Article

Similar Reads

Maximum edge removal from tree to make even forest
Given an undirected tree which has even number of vertices, we need to remove the maximum number of edges from this tree such that each connected component of the resultant forest has an even number of vertices. Examples: In above shown tree, we can remove at max 2 edges 0-2 and 0-4 shown in red such that each connected component will have even num
10 min read
Minimize deletion of edges to convert Tree into a forest of size at most N/2
Given a tree with N nodes, numbered from 0 to N - 1, the task is to find the minimum number of deletion of edges, such that, the tree is converted into a forest where each tree in the forest can have size less than equal to ⌊N/2⌋. Examples: Input: N = 3, edges = [[0, 1], [0, 2]] 0 / \ 1 2Output: 2Explanation: The maximum size of each tree after rem
14 min read
Print even positioned nodes of even levels in level order of the given binary tree
Given a binary tree, print even positioned nodes of even level in level order traversal. The root is considered at level 0, and the left most node of any level is considered as a node at position 0. Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 / \ 7 8 / \ 9 10 Output: 1 4 6 9 Input: 2 / \ 4 15 / / 45 17 Output: 2 45 Approach: To print nodes level by leve
8 min read
Modify Binary Tree by replacing all nodes at even and odd levels by their nearest even or odd perfect squares respectively
Given a Binary Tree consisting of N nodes, the task is to replace all the nodes that are present at even-numbered levels in a Binary Tree with their nearest even perfect square and replace nodes at odd-numbered levels with their nearest odd perfect square. Examples: Input: 5 / \ 3 2 / \ 16 19 Output: 9 / \ 4 4 / \ 9 25 Explanation: Level 1: Nearest
13 min read
Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
Given a tree, and the weights (in the form of strings) of all the nodes, the task is to count the nodes whose weighted string when concatenated with the strings of the sub-tree nodes becomes a pangram. Pangram: A pangram is a sentence containing every letter of the English Alphabet. Examples: Input: Output: 1 Only the weighted string of sub-tree of
7 min read
Node whose removal minimizes the maximum size forest from an N-ary Tree
Given an n-ary tree T, the task is to find a node whose removal minimizes the maximum size of all forests(connected components) generated. Examples: Input: 1 / | \ 2 3 4 / \ 5 6Output: 1Explanation:There are six nodes which can be removed to form forests:Remove(1): Largest Forest size is 3Remove(2): Largest Forest size is 3Remove(3): Largest Forest
7 min read
Convert given Binary Tree to Symmetric Tree by adding minimum number of nodes
Given a Binary Tree, the task is to convert the given Binary Tree to the Symmetric Tree by adding the minimum number of nodes in the given Tree. Examples: Input: Output: Input: Output: Approach: To solve this problem, follow the below steps: Make a function buildSymmetricTree which will accept two parameters root1 and root2.Here, root1 and root2, a
8 min read
Append odd position nodes in reverse at the end of even positioned nodes in a Linked List
Given a linked list. The task is to segregate its even and odd position nodes in such a way that odd position nodes appear before even positioned nodes all the even positioned nodes must be in reverse order. Examples: Input: 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 6 -&gt; NULL Output : 1 -&gt; 3 -&gt; 5 -&gt; 6 -&gt; 4 -&gt; 2 -&gt; NULL Input : 1
11 min read
Print levels with odd number of nodes and even number of nodes
Given an N-ary tree, print all the levels with odd and even numbers of nodes in it. Examples: For example consider the following tree 1 - Level 1 / \ 2 3 - Level 2 / \ \ 4 5 6 - Level 3 / \ / 7 8 9 - Level 4The levels with odd number of nodes are: 1 3 4 The levels with even number of nodes are: 2Note: The level numbers starts from 1. That is, the r
15+ min read
Find a set of at most N/2 nodes from a Graph such that all remaining nodes are directly connected to one of the chosen nodes
Given an integer N, representing the number of nodes present in an undirected graph, with each node valued from 1 to N, and a 2D array Edges[][], representing the pair of vertices connected by an edge, the task is to find a set of at most N/2 nodes such that nodes that are not present in the set, are connected adjacent to any one of the nodes prese
12 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg