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.
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 number of vertices.
As we need connected components that have even number of vertices so when we get one component we can remove the edge that connects it to the remaining tree and we will be left with a tree with even number of vertices which will be the same problem but of smaller size, we have to repeat this algorithm until the remaining tree cannot be decomposed further in the above manner.
We will traverse the tree using DFS which will return the number of vertices in the component of which the current node is the root. If a node gets an even number of vertices from one of its children then the edge from that node to its child will be removed and result will be increased by one and if the returned number is odd then we will add it to the number of vertices that the component will have if the current node is the root of it.
1) Do DFS from any starting node as tree is connected. 2) Initialize count of nodes in subtree rooted under current node as 0. 3) Do following recursively for every subtree of current node. a) If size of current subtree is even, increment result by 1 as we can disconnect the subtree. b) Else add count of nodes in current subtree to current count.
Please see below code for better understanding,
Time Complexity : O(n) where n is number of nodes in tree.
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Maximum Possible Edge Disjoint Spanning Tree From a Complete Graph
- Convert a tree to forest of even nodes
- Minimum edge reversals to make a root
- Tree, Back, Edge and Cross Edges in DFS of Graph
- Check if removing an edge can divide a Binary Tree in two halves
- Count number of trees in a forest
- Minimum Operations to make value of all vertices of the tree Zero
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- Make a tree with n vertices , d diameter and at most vertex degree k
- Maximum spiral sum in Binary Tree
- Node having maximum sum of immediate children and itself in n-ary tree
- Maximum Path Sum in a Binary Tree
- Maximum width of a binary tree
- Maximum sum from a tree with adjacent levels not allowed
- Sum of nodes at maximum depth of a Binary Tree | Set 2