Write a function that returns true if a given undirected graph is tree and false otherwise. For example, the following graph is a tree.
But the following graph is not a tree.
An undirected graph is tree if it has 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 above two properties.
How to detect cycle 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 parent of v, then there is a cycle in 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 graph is connected, otherwise not.
link brightness_4 code
// A C++ Program to check whether a graph is tree or not
// Class for an undirected graph
intV; // No. of vertices
list<int> *adj; // Pointer to an array for adjacency lists
boolisCyclicUtil(intv, boolvisited, intparent);
Graph(intV); // Constructor
voidaddEdge(intv, intw); // to add an edge to graph
boolisTree(); // returns true if graph is tree
this->V = V;
adj = newlist<int>[V];
adj[v].push_back(w); // Add w to v’s list.
adj[w].push_back(v); // Add v to w’s list.
// A recursive function that uses visited and parent to
// detect cycle in subgraph reachable from vertex v.