Best algorithm to determine if an undirected graph

2020-02-06 07:53发布

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

2条回答
我只想做你的唯一
2楼-- · 2020-02-06 08:19

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.

查看更多
何必那么认真
3楼-- · 2020-02-06 08:21

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

查看更多
登录 后发表回答