Solution: The minimum vertex cover for a general graph is a NP-hard problem. However, for a tree, there is a linear solution. The idea here is to do DFS search plus post-order traversal. If we encounter a leaf node and the edge connecting this leaf node with its parent, we know in order to construct a vertex cover, we must include at least one of the node (the leaf node, or its parent). Here we can use a greedy approach. We can see selecting the leaf doesn't give us any extra benefit, while selecting the parent can give us some benefit, since the parent must be also connected to other nodes. By selecting the parent node, we can further "cover" some extra edges. With this strategy in mind, our algorithm is as follow:
- we do a DFS search. When a DFS call on a child node returns, we check if the child and the parent are both unselected. If yes, we select the parent node.
- After all the DFS finishes (we traverse the tree), those selected nodes form the minimum vertex cover. The cost is O(N).
void min_vertex_cover(TreeNode *root)
{
if(isLeaf(root)) return;
for(int i=0; i<root->num_of_children; i++)
{
min_vertex_cover(root->children[i]);
if(!root->selected && !root->children[i]->selected)
root->selected = true;
}
}