Given an undirected graph, check if it is a tree or not. In other words, check if a given undirected graph is an Acyclic Connected Graph or not.

For example, the graph shown on the right is a tree, and the graph on the left is not a tree as it contains a cycle 0—1—2—3—4—5—0.

 
Acyclic Connected Graph    Tree

Practice this problem

 
Recommended Read:

Types of edges involved in DFS and relation between them

Check if an undirected graph contains a cycle or not

 
A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any acyclic connected graph is a tree. We can easily determine the acyclic connected graph by doing a DFS traversal on the graph. When we do a DFS from any vertex v in an undirected graph, we may encounter a back-edge that points to one of the ancestors of the current vertex v in the DFS tree. Each “back edge” defines a cycle in an undirected graph. If the back edge is x —> y, then since y is the ancestor of node x, we have a path from y to x. So, we can say that the path y ~~ x ~ y forms a cycle. (Here, ~~ represents one more edge in the path, and ~ represents a direct edge) and is not a tree.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The graph is not a tree

Java


Download  Run Code

Output:

The graph is not a tree

Python


Download  Run Code

Output:

The graph is not a tree

The time complexity of the above solution is O(V + E), where V and E are the total number of vertices and edges in the graph, respectively.