I'm thinking that there are two cases for each sub-tree: the root is in the independent set and the root is not in the set. How to write a recursive algorithm for finding the number of independent sets in a tree? The tree is n-ary.
https://en.wikipedia.org/wiki/Independent_set_(graph_theory)
This is my solution so far, but it isn't correct. The variable parentIncluded is equal to true if the parent of the current subtree is already included in the independent set, thus the root of the current subtree can't be added to the independent set. If parentIncluded is equal to false, then the root of the current subtree can be added to the independent set. There are two cases for when parentIncluded is false. The first case: Add the root to the set. Second case: don't add the root.
public static int numberOfIndependentSets(Binary root) {
if (root == null) {
return 1;
}
return numberOfIndependentSets(root, false) + 1;
}
private static int numberOfIndependentSets(Binary current, boolean parentIncluded) {
if (current.left == null && current.right == null) {
if (parentIncluded) {
return 0;
} else {
return 1;
}
}
int total = 0;
if (parentIncluded) {
int left = numberOfIndependentSets(current.left, false);
int right = numberOfIndependentSets(current.right, false);
total += (left + 1) * (right + 1) - 1;
} else {
// include current node
int left = numberOfIndependentSets(current.left, true);
int right = numberOfIndependentSets(current.right, true);
total = (left+1) *( right +1);
// not include current node
left = numberOfIndependentSets(current.left, false);
right = numberOfIndependentSets(current.right, false);
total += (left+1) * (right+1) -1;
}
return total;
}