What is the time complexity of the Best algorithm to determine if an undirected graph is a tree??
can we say Big-oh(n) , with n vertices??
What is the time complexity of the Best algorithm to determine if an undirected graph is a tree??
can we say Big-oh(n) , with n vertices??
Yes, it is O(n).
Pick a starting node, and perform depth first traversal. If you visit a node more than once, it isn't a tree.
Yes, it is O(n). With a depth-first search in a directed graph has 3 types of non-tree edges - cross, back and forward.
For an undirected case, the only kind of non-tree edge is a back edge. So, you just need to search for back edges.
In short, choose a starting vertex. Traverse and keep checking if the edge encountered is a back edge. If you find n-1 tree edges without finding back-edges and then, run out of edges, you're gold.
(Just to clarify - a
back edge
is one where the vertex at the other end has already been encountered - and because of the properties of undirected graphs, the vertex at the other end would be an ancestor of the present node in the tree that is being constructed.)