1

I came across this posting from a while back:

Best algorithm to determine if an undirected graph is a tree

It says that to determine if an undirected graph is a tree, you just have to check if it has a cycle. However, don't you have to make sure the graph is connected? I was taught that a tree is connected and acyclic. How is checking only for acyclicity sufficient?

Thanks.

Community
  • 1
  • 1
user1317750
  • 51
  • 2
  • 8
  • for program implementation [check this](http://www.msccomputerscience.com/2014/04/wap-to-check-whether-graph-is-connected.html) – ARJUN Sep 17 '14 at 06:33

1 Answers1

0

You're right. If the graph is acyclic, then it's a forest. In addition, if it only has one component, then it's a tree.

What the algorithm mentioned does is look for back edges. If it finds one, then the graph is not a tree. If it doesn't find one and the algorithm visited n-1 edges before running out of edges, then it IS a tree, because having visited n-1 edges means that the graph is indeed connected (a tree with n vertices has n-1 edges). If the algorithm ran out of edges but didn't reach n-1 visited edges, then it means the graph is not connected, hence it is not a tree.

Juan Pablo Rinaldi
  • 3,394
  • 1
  • 20
  • 20