VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-given-graph-tree/

⇱ Check if a given graph is tree or not - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if a given graph is tree or not

Last Updated : 23 Jul, 2025

Write a function that returns true if a given undirected graph is a tree and false otherwise. For example, the following graph is a tree.
 

πŸ‘ cycleGraph


But the following graph is not a tree. 
 

πŸ‘ cycleGraph


Approach 1:

An undirected graph is a tree if it has the following properties. 

  1. There is no cycle. 
  2. The graph is connected.

For an undirected graph, we can either use BFS or DFS to detect the above two properties.

How to detect cycles in an undirected graph? 
We can either use BFS or DFS. For every visited vertex β€˜v’, if there is an adjacent β€˜u’ such that u is already visited and u is not the parent of v, then there is a cycle in the graph. If we don’t find such an adjacent for any vertex, we say that there is no cycle (See Detect cycle in an undirected graph for more details).

How to check for connectivity? 
Since the graph is undirected, we can start BFS or DFS from any vertex and check if all vertices are reachable or not. If all vertices are reachable, then the graph is connected, otherwise not.
Implementation: 


Output
Graph is Tree
Graph is not Tree

Time Complexity: O(V + E) 
Auxiliary Space: O(V) as we are using the visited array.

Approach 2:

However if we observe carefully the definition of tree and its structure we will deduce that if a graph is connected and has n - 1 edges exactly then the graph is a tree.

Proof: 

Since we have assumed our graph of n nodes to be connected, it must have at least n - 1 edges inside it. Now if we try to add one more edge than the n - 1 edges already the graph will end up forming a cycle and thus will not satisfy the definition of tree. Therefore, it is necessary for a connected graph to have exactly n - 1 edges to avoid forming cycle


Output
Graph is Tree
Graph is not Tree

Time Complexity: O(V + E) For performing the DFS traversal
Auxiliary Space: O(V) For storing the visited array

Comment
Article Tags: