# C++ Program to Check if a Directed Graph is a Tree or Not Using DFS

C++Server Side ProgrammingProgramming

A graph is a tree if it does not contain any cycle. This is a C++ program to check whether a directed graph is tree or not using DFS.

## Algorithm

Begin
function cyclicUtil() :
a) Mark the current node as visited and part of recursion stack
b) Recur for all the vertices adjacent to this vertex.
c) Remove the vertex from recursion stack.
function cyclic() :
a) Mark all the vertices as not visited and not part of recursion stack
b) Call the CyclicUtill() function to detect cycle in different trees
End

## Example

#include<iostream>
#include <list>
#include <limits.h>
using namespace std;
class G {
int n;
bool CyclicUtil(int v, bool visited[], bool *rs);
public:
G(int V); // Constructor
bool cyclic();
};
G::G(int n) {
this->n = n;
}
void G::addEd(int v, int u) //to add edges in the graph {
}
bool G::CyclicUtil(int v, bool visited[], bool *recurS) {
if (visited[v] == false) {
visited[v] = true; //Mark the current node as visited and part of recursion stack
recurS[v] = true;
// Recur for all the vertices adjacent to this vertex.
list<int>::iterator i;
if (!visited[*i] && CyclicUtil(*i, visited, recurS))
return true;
else if (recurS[*i])
return true;
}
}
recurS[v] = false; //Remove the vertex from recursion stack.
return false;
}
//check if the graph is tree or not
bool G::cyclic() {
//Mark all the vertices as not visited and not part of recursion stack
bool *visited = new bool[n];
bool *recurS = new bool[n];
for (int i = 0; i < n; i++) {
visited[i] = false;
recurS[i] = false;
}
// Call the CyclicUtill() function to detect cycle in different trees
for (int i = 0; i < n; i++)
if (CyclicUtil(i, visited, recurS))
return true;
return false;
}
int main() {
G g(4);
}
Directed Graph isn't a tree