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 number of
vertices.
class Solution {
    public class Pair {
        int edgeRemovals;
        int countNodes;

        Pair(int e, int c) {
            edgeRemovals = e;
            countNodes = c;
        }
    }

    public Pair helper(Node node) {
        if (node == null)
            return new Pair(0, 0);

        Pair ans = new Pair(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;
    }

    public Pair countMaximumEdgeRemovalForEvenNodesForest(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 parts
        if (ans.countNodes % 2 != 0)
            ans.countNodes = 0;
        return ans;
    }
}

Last updated