![]() |
VOOZH | about |
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.
But the following graph is not a tree.
Approach 1:
An undirected graph is a tree if it has the following properties.
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:
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.
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