- #1

evinda

Gold Member

MHB

- 3,836

- 0

I want to write an algorithm that finds an optimal vertex cover of a tree in linear time $O(n)$, where $n$ is the number of the vertices of the tree..

A vertex cover of a graph $G=(V,E)$ is a subset $W$ of $V$ such that for every edge $(a,b)$ in $E$, a is in $W$ or $b$ is in $W$.In a vertex cover we need to have at least one vertex for each edge.

If we pick a non-leaf, it can cover more than one edge.

That's why I thought we can do it as follows:

We visit the root of the tree, then we visit one of its children, a child of the latter that we visited and so on..

Then if we have reached at a leaf, we check if we already have taken its father for the optimal vertex cover, and if not we pick it. Then, if the vertex that we picked for the optimal vertex cover has also other children, we pick the first of them and visit the leftmost children recursively and if we reach at the leaf and its father hasn't been chosen for the desired vertex cover, we choose it and so on.

I have written the following algorithm:

Code:

```
DFS(node x){
discovered[x]=1;
for each (v in Adj(x)){
if discovered[v]==0{
DFS(v);
if (v->taken==0){
x<-taken=1;
}
}
}
}
```

Its time complexity is $T(n)=\sum_{i=1}^{|V|} O(|V_i|+|E_i|) \leq \sum_{i=1}^{|V|} O(|E_i|) \leq \sum_{i=1}^{|V|} O(|E|)=O(|V| \cdot |E|)$.

($|V_i|, |E_i|$ are the number of vertices and edges respectively of the subtrees at the root of which we call DFS )

Is the time complexity I found right? Or have I calculated it wrong? (Thinking)