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 number of
vertices.
classSolution {publicclassPair {int edgeRemovals;int countNodes;Pair(int e,int c) { edgeRemovals = e; countNodes = c; } }publicPairhelper(Node node) {if (node ==null)returnnewPair(0,0);Pair ans =newPair(0,1);Pair left =helper(node.left);ans.edgeRemovals+=left.edgeRemovals;ans.countNodes+=left.countNodes;Pair right =helper(node.right);ans.edgeRemovals+=right.edgeRemovals;ans.countNodes+=right.countNodes;if (left.countNodes%2==0&&left.countNodes>0)ans.edgeRemovals+=1;if (right.countNodes%2==0&&right.countNodes>0)ans.edgeRemovals+=1;return ans; }publicPaircountMaximumEdgeRemovalForEvenNodesForest(Node node,Node root) {Pair ans =helper(node);// If number of nodes is odd then there is no we can// split it to get 2 even partsif (ans.countNodes%2!=0)ans.countNodes=0;return ans; }}