Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

7/10/2017 Check if a given graph is tree or not - GeeksforGeeks

GeeksforGeeks Custom Search


A computer science portal for geeks
Practice GATE CS Placements Videos Contribute
Login/Register

Check if a given graph is tree or not


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

http://www.geeksforgeeks.org/check-given-graph-tree/ 1/10
bool Graph::isTree()
7/10/2017 Check if a given graph is tree or not - GeeksforGeeks
{
return (!isCyclic_UnDirectedGraph())
already visited and u is not parent of && isInDirectedGraphStonglyConnectd();
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).
bool Graph::isInDirectedGraphStonglyConnectd()
{ How to check for connectivity?
bool* visited = new bool[V];
Since
for (intthe
i =graph
0; i is
< undirected,
V; ++i) we can start BFS or DFS from any vertex and check if all vertices are
visited[i] = false;
reachable or not. If all vertices are reachable, then graph is connected, otherwise not.

DFSUtils(visited, 0);
C++
for (int i = 0; i < V; ++i)
{ // A C++ Program to check whether a graph is tree or not
if (!visited[i])
#include<iostream>
return
#include false;
<list>
} #include <limits.h>
return
using true;
namespace std;
}
// Class for an undirected graph
class Graph
bool Graph::isCyclic_UnDirectedGraphUtils(bool* visited, int v, int parent)
{ {
int V;= true;
visited[v] // No. of vertices
list<int> *adj; // Pointer to an array for adjacency lists
bool isCyclicUtil(int v, bool visited[], int parent);
for (auto& vertex : adj[v])
public:
{ Graph(int V); // Constructor
ifvoid
(visited[vertex]
addEdge(int v,&&int
vertex
w); != //
parent)
to add an edge to graph
return true;
bool isTree(); // returns true if graph is tree
};
if (!visited[vertex])
Graph::Graph(int V)
isCyclic_UnDirectedGraphUtils(visited, vertex, v);
} {
this->V = V;
returnadj = new list<int>[V];
false;
} }

void Graph::addEdge(int v, int w)


{
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.
bool Graph::isCyclicUtil(int v, bool visited[], int parent)
{
// Mark the current node as visited
visited[v] = true;

// Recur for all the vertices adjacent to this vertex


list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
{
// If an adjacent is not visited, then recur for
// that adjacent
if (!visited[*i])
{
if (isCyclicUtil(*i, visited, v))
return true;
}

// If an adjacent is visited and not parent of current


// vertex, then there is a cycle. ▲
else if (*i != parent)
return true;
}
return false;
}
http://www.geeksforgeeks.org/check-given-graph-tree/ 2/10
7/10/2017 Check if a given graph is tree or not - GeeksforGeeks
}

// Returns true if the graph is a tree, else false.


bool Graph::isTree()
{
// Mark all the vertices as not visited and not part of
// recursion stack
bool *visited = new bool[V];
for (int i = 0; i < V; i++)
visited[i] = false;

// The call to isCyclicUtil serves multiple purposes.


// It returns true if graph reachable from vertex 0
// is cyclcic. It also marks all vertices reachable
// from 0.
if (isCyclicUtil(0, visited, -1))
return false;

// If we find a vertex which is not reachable from 0


// (not marked by isCyclicUtil(), then we return false
for (int u = 0; u < V; u++)
if (!visited[u])
return false;

return true;
}

// Driver program to test above functions


int main()
{
Graph g1(5);
g1.addEdge(1, 0);
g1.addEdge(0, 2);
g1.addEdge(0, 3);
g1.addEdge(3, 4);
g1.isTree()? cout << "Graph is Tree\n":
cout << "Graph is not Tree\n";

Graph g2(5);
g2.addEdge(1, 0);
g2.addEdge(0, 2);
g2.addEdge(2, 1);
g2.addEdge(0, 3);
g2.addEdge(3, 4);
g2.isTree()? cout << "Graph is Tree\n":
cout << "Graph is not Tree\n";

return 0;
}
Run on IDE

Java
// A Java Program to check whether a graph is tree or not
import java.io.*;
import java.util.*;

// This class represents a directed graph using adjacency


// list representation
class Graph
{
private int V; // No. of vertices ▲
private LinkedList<Integer> adj[]; //Adjacency List

// Constructor

Graph(int v)
http://www.geeksforgeeks.org/check-given-graph-tree/ 3/10
7/10/2017 Check if a given graph is tree or not - GeeksforGeeks
Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
}

// Function to add an edge into the graph


void addEdge(int v,int w)
{
adj[v].add(w);
adj[w].add(v);
}

// A recursive function that uses visited[] and parent


// to detect cycle in subgraph reachable from vertex v.
Boolean isCyclicUtil(int v, Boolean visited[], int parent)
{
// Mark the current node as visited
visited[v] = true;
Integer i;

// Recur for all the vertices adjacent to this vertex


Iterator<Integer> it = adj[v].iterator();
while (it.hasNext())
{
i = it.next();

// If an adjacent is not visited, then recur for


// that adjacent
if (!visited[i])
{
if (isCyclicUtil(i, visited, v))
return true;
}

// If an adjacent is visited and not parent of


// current vertex, then there is a cycle.
else if (i != parent)
return true;
}
return false;
}

// Returns true if the graph is a tree, else false.


Boolean isTree()
{
// Mark all the vertices as not visited and not part
// of recursion stack
Boolean visited[] = new Boolean[V];
for (int i = 0; i < V; i++)
visited[i] = false;

// The call to isCyclicUtil serves multiple purposes


// It returns true if graph reachable from vertex 0
// is cyclcic. It also marks all vertices reachable
// from 0.
if (isCyclicUtil(0, visited, -1))
return false;

// If we find a vertex which is not reachable from 0


// (not marked by isCyclicUtil(), then we return false
for (int u = 0; u < V; u++)
if (!visited[u])
return false; ▲

return true;
}

http://www.geeksforgeeks.org/check-given-graph-tree/ 4/10
7/10/2017 Check if a given graph is tree or not - GeeksforGeeks

// Driver method
public static void main(String args[])
{
// Create a graph given in the above diagram
Graph g1 = new Graph(5);
g1.addEdge(1, 0);
g1.addEdge(0, 2);
g1.addEdge(0, 3);
g1.addEdge(3, 4);
if (g1.isTree())
System.out.println("Graph is Tree");
else
System.out.println("Graph is not Tree");

Graph g2 = new Graph(5);


g2.addEdge(1, 0);
g2.addEdge(0, 2);
g2.addEdge(2, 1);
g2.addEdge(0, 3);
g2.addEdge(3, 4);

if (g2.isTree())
System.out.println("Graph is Tree");
else
System.out.println("Graph is not Tree");

}
}
// This code is contributed by Aakash Hasija
Run on IDE

Python
# Python Program to check whether
# a graph is tree or not

from collections import defaultdict

class Graph():

def __init__(self, V):


self.V = V
self.graph = defaultdict(list)

def addEdge(self, v, w):


# Add w to v ist.
self.graph[v].append(w)
# Add v to w list.
self.graph[w].append(v)

# A recursive function that uses visited[]


# and parent to detect cycle in subgraph
# reachable from vertex v.
def isCyclicUtil(self, v, visited, parent):

# Mark current node as visited


visited[v] = True

# Recur for all the vertices adjacent


# for this vertex
for i in self.graph[v]: ▲
# If an adjacent is not visited,
# then recur for that adjacent
if visited[i] == False:

if self.isCyclicUtil(i,
http://www.geeksforgeeks.org/check-given-graph-tree/ visited, v) == True: 5/10
7/10/2017 Check if a given graph is tree or not - GeeksforGeeks
if self.isCyclicUtil(i, visited, v) == True:
return True

# If an adjacent is visited and not


# parent of current vertex, then there
# is a cycle.
elif i != parent:
return True

return False

# Returns true if the graph is a tree,


# else false.
def isTree(self):
# Mark all the vertices as not visited
# and not part of recursion stack
visited = [False] * self.V

# The call to isCyclicUtil serves multiple


# purposes. It returns true if graph reachable
# from vertex 0 is cyclcic. It also marks
# all vertices reachable from 0.
if self.isCyclicUtil(0, visited, -1) == True:
return False

# If we find a vertex which is not reachable


# from 0 (not marked by isCyclicUtil(),
# then we return false
for i in range(self.V):
if visited[i] == False:
return False

return True

# Driver program to test above functions


g1 = Graph(5)
g1.addEdge(1, 0)
g1.addEdge(0, 2)
g1.addEdge(0, 3)
g1.addEdge(3, 4)
print "Graph is a Tree" if g1.isTree() == True \
else "Graph is a not a Tree"

g2 = Graph(5)
g2.addEdge(1, 0)
g2.addEdge(0, 2)
g2.addEdge(2, 1)
g2.addEdge(0, 3)
g2.addEdge(3, 4)
print "Graph is a Tree" if g2.isTree() == True \
else "Graph is a not a Tree"

# This code is contributed by Divyanshu Mehta


Run on IDE

Output:

Graph is Tree
Graph is not Tree

http://www.geeksforgeeks.org/check-given-graph-tree/ 6/10
7/10/2017 Check if a given graph is tree or not - GeeksforGeeks

Check if a given graph is tree or not | GeeksforGeeks

Thanks to Vinit Verma for suggesting this problem and initial solution. Please write comments if you
find anything incorrect, or you want to share more information about the topic discussed above

http://www.geeksforgeeks.org/check-given-graph-tree/ 7/10
7/10/2017 Check if a given graph is tree or not - GeeksforGeeks

http://www.geeksforgeeks.org/check-given-graph-tree/ 8/10
7/10/2017 Check if a given graph is tree or not - GeeksforGeeks

DEE MANNEQUIN LEATHER


SOFT GYM BAG (BROWN)
Rs. 379.00
(details + delivery)

DEE MANNEQUIN VINTAGE


BLACK 79 LTRS …
Rs. 379.00
(details + delivery)

F GEAR ASTIR BAG


POLYESTER 18 LTRS …
Rs. 599.00
(details + delivery)

GATE CS Corner Company Wise Coding Practice

Graph Trees BFS DFS

Recommended Posts:

Word Ladder (Length of shortest chain to reach a target word)


Serialize and Deserialize a Binary Tree
Karger’s algorithm for Minimum Cut | Set 1 (Introduction and Implementation)
Check if a graph is strongly connected | Set 1 (Kosaraju using DFS)
Graph and its representations

http://www.geeksforgeeks.org/check-given-graph-tree/ 9/10
7/10/2017 Check if a given graph is tree or not - GeeksforGeeks

(Login to Rate and Mark)

Average Difficulty : 2.8/5.0


2.8 Based on 10 vote(s)
Add to TODO List
Mark as DONE

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.

Load Comments Share this post!

@geeksforgeeks, Some rights reserved Contact Us! About Us! Advertise with us! Privacy
Policy

http://www.geeksforgeeks.org/check-given-graph-tree/ 10/10

You might also like