Check if a given graph is tree or not

Data StructureAlgorithmsGraph Algorithms

In this problem, one undirected graph is given, we have to check the graph is tree or not. We can simply find it by checking the criteria of a tree. A tree will not contain a cycle, so if there is any cycle in the graph, it is not a tree.

We can check it using another approach, if the graph is connected and it has V-1 edges, it could be a tree. Here V is the number of vertices in the graph.

Input and Output

The adjacency matrix.
0 0 0 0 1
0 0 0 0 1
0 0 0 0 1
0 0 0 0 1
1 1 1 1 0

The Graph is a tree


isCycle(u, visited, parent)

Input: The start vertex u, the visited list to mark visited or not, the parent vertex.

Output: True if there is a cycle in the graph.

   mark u as visited
   for all vertex v which are adjacent with u, do
      if v is visited, then
         if isCycle(v, visited, u) = true, then
            return true
         else if v ≠ parent, then
            return true
   return false


Input: The undirected graph.

Output: True when the graph is a tree.

   define a visited array to mark which node is visited or not
   initially mark all node as unvisited
   if isCycle(0, visited, φ) is true, then //the parent of starting vertex is null
      return false
   if the graph is not connected, then
      return false
   return true otherwise


#define NODE 5
using namespace std;

int graph[NODE][NODE] = {
   {0, 1, 1, 1, 0},
   {1, 0, 1, 0, 0},
   {1, 1, 0, 0, 0},
   {1, 0, 0, 0, 1},
   {0, 0, 0, 1, 0}
bool isCycle(int u, bool visited[], int parent) {
   visited[u] = true;    //mark v as visited
   for(int v = 0; v<NODE; v++) {
      if(graph[u][v]) {
         if(!visited[v]) {     //when the adjacent node v is not visited
            if(isCycle(v, visited, u)) {
               return true;
         } else if(v != parent) {    //when adjacent vertex is visited but not parent
            return true;    //there is a cycle
   return false;

bool isTree() {
   bool *vis = new bool[NODE];

   for(int i = 0; i<NODE; i++)
      vis[i] = false;    //initialize as no node is visited
   if(isCycle(0, vis, -1))    //check if there is a cycle or not
      return false;
   for(int i = 0; i<NODE; i++) {
      if(!vis[i])    //if there is a node, not visited by traversal, graph is not connected
         return false;
   return true;

int main() {
      cout << "The Graph is a Tree.";
      cout << "The Graph is not a Tree.";


The Graph is a Tree.
Published on 10-Jul-2018 12:03:37