Please help find error in this code (vertex cover algorithm)

graph
vertex_cover

#1

I am implementing vertex cover in tree (polynomial time algorithm) after reading the concept at geeksforgeeks . I am getting runtime error. I am storing the tree as an adjacency-list form of a graph (as tree is basically a graph).

All the implementaions I found implement the tree using structure (like we do in binary tree with left and right pointer). So they have a condition for when root is NULL.

Since the tree is represented as adjacency list, I don’t think that condition is necessary (just thinking). Please tell me the reason if that part is causing the error and if so, why?

How can I fix the problem?

My code

Please help …!!!

[EDIT] - I found an error, since the graph is undirected, when visiting the child node, there is a path back to the parent node. So this is giving an infinite loop. Use of recursion is taking stack memory causing segmentation fault. I cannot find a way around it. Making the graph directed is not working and adding a visit array like we do in DFS is giving wrong answer.

code with visit array


#2

Found the error and I think I have solved it.

Also another approach :