Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create graphIsTreeOrNot #7026

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions graphIsTreeOrNot
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import java.io.*;
import java.util.*;

class Graph
{
private int V;
private LinkedList<Integer> adj[];


@SuppressWarnings("unchecked")
Graph(int v)
{
V = v;
adj = new LinkedList[V];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList<Integer>();
}

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

boolean isCyclicUtil(int v, boolean visited[], int parent)
{
// Mark the current node as visited
visited[v] = true;
Integer i;

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

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

else if (i != parent)
return true;
}
return false;
}

// Returns true if the graph is a tree, else false.
boolean isTree()
{

boolean visited[] = new boolean[V];
for (int i = 0; i < V; i++)
visited[i] = false;
if (isCyclicUtil(0, visited, -1))
return false;

for (int u = 0; u < V; u++)
if (!visited[u])
return false;

return true;
}

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");

}
}