5

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??

rakesh
  • 123
  • 1
  • 2
  • 7

2 Answers2

5

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.)

Navneet
  • 9,590
  • 11
  • 34
  • 51
2

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.

Anthony Blake
  • 5,328
  • 2
  • 25
  • 24