Largest Independent Set Problem
Pattern: DP on trees
Pick the most nodes so that no chosen node is the parent of another chosen node. Each node returns two numbers: the best with it chosen (its children not) and without it (each child either way).
The problem
Return the size of the largest set of nodes in the binary tree with no two chosen nodes joined by an edge.
Think first
- If a node is chosen, what about its children?
- If it is not, what can the children do?
- Why return two numbers?
Hints
Brute force, and why it fails
Try every subset of nodes: 2ⁿ.
The key insight
Each subtree's best with and without its root is all a parent needs.
Dry run
The tree 10 with children 20, 30; 20 has 40 and 50; 30 has 60; 50 has 70 and 80.
Step 1 of 2
The plan
best(n): (take, skip)
take = 1 + skip of both children
skip = max(take, skip) of each child, added
Complexity
- Time
O(n)- Space
O(h)
One post-order pass; h is the height.
Edge cases
- One node: 1.
- A chain: about half.
- A perfect tree.
I've built my logic, show the code
Java
class Solution {
public int LISS(TreeNode root) {
int[] r = best(root);
return Math.max(r[0], r[1]);
}
private int[] best(TreeNode n) { // {largest set with n in it, largest set without n}
if (n == null) return new int[]{0, 0};
int[] l = best(n.left), r = best(n.right);
return new int[]{1 + l[1] + r[1], Math.max(l[0], l[1]) + Math.max(r[0], r[1])}; // with n, its children are out
}
}C++
class Solution {
public:
int LISS(TreeNode* root) {
pair<int, int> r = best(root);
return max(r.first, r.second);
}
pair<int, int> best(TreeNode* n) { // {largest set with n in it, largest set without n}
if (n == NULL) return make_pair(0, 0);
pair<int, int> l = best(n->left), r = best(n->right);
return make_pair(1 + l.second + r.second, max(l.first, l.second) + max(r.first, r.second)); // with n, children out
}
};Python
class Solution:
def LISS(self, root) -> int:
def best(n): # (largest set with n in it, largest set without n)
if n is None:
return 0, 0
lw, lo = best(n.left)
rw, ro = best(n.right)
return 1 + lo + ro, max(lw, lo) + max(rw, ro) # with n, its children are out
return max(best(root))Common mistakes
- Choosing every other level.
- Returning only one number.