Here is a link to a similar question with a good answer: Java Algorithm for finding the largest set of independent nodes in a binary tree.
I came up with a different answer, but my professor says it won’t work and I’d like to know why (he doesn’t answer email).
The question:
Given an array A with n integers, its indexes start with 0 (i.e,
A[0],
A[1], …,A[n-1]). We can interpret A as a binary tree in which the two
children ofA[i]areA[2i+1]andA[2i+2], and the value of each
element is the node weight of the tree. In this tree, we say that a
set of vertices is “independent” if it does not contain any
parent-child pair. The weight of an independent set is just the
summation of all weights of its elements. Develop an algorithm to
calculate the maximum weight of any independent set.
The answer I came up with used the following two assumptions about independent sets in a binary tree:
- All nodes on the same level are independent from each other.
- All nodes on alternating levels are independent from each other (there are no parent/child relations)
Warning: I came up with this during my exam, and it isn’t pretty, but I just want to see if I can argue for at least partial credit.
So, why can’t you just build two independent sets (one for odd levels, one for even levels)?
If any of the weights in each set are non-negative, sum them (discarding the negative elements because that won’t contribute to a largest weight set) to find the independent set with the largest weight.
If the weights in the set are all negative (or equal to 0), sort it and return the negative number closest to 0 for the weight.
Compare the weights of the largest independent set from each of the two sets and return it as the final solution.
My professor claims it won’t work, but I don’t see why. Why won’t it work?
Your algorithm doesn’t work because the set of nodes it returns will be either all from odd levels, or all from even levels. But the optimal solution can have nodes from both.
For example, consider a tree where all weights are 0 except for two nodes which have weight 1. One of these nodes is at level 1 and the other is at level 4. The optimal solution will contain both these nodes and have weight 2. But your algorithm will only give one of these nodes and have weight 1.