Best algorithm to determine if an undirected graph is a tree

徘徊边缘 提交于 2019-11-28 12:26:26

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!