Skip to content

Commit be67bf6

Browse files
committed
Added is graph tree
1 parent e7ec181 commit be67bf6

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

Other/IsGraphTree.java

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import java.util.*;
2+
3+
/**
4+
* Check whether a given graph is a tree
5+
*
6+
* Tags: Graph, Tree, DFS
7+
*/
8+
class IsGraphTree<T> {
9+
public static void main(String[] args) {
10+
11+
}
12+
13+
/**
14+
* # of edges = # of vertices - 1
15+
* No cycles, use dfs to do cycle detection
16+
* Connected, which means all nodes are visited
17+
*/
18+
public boolean checkTree(Graph G, Vertex<T> V) {
19+
if (G.edges.size() != G.vertices.size() - 1) return false;
20+
HashSet<Vertex<T>> set = new HashSet<Vertex<T>>();
21+
boolean hasCycle = dfs(G, V, set);
22+
if (hasCycle) return false;
23+
if (set.size() != G.vertices.size()) return false;
24+
return true;
25+
}
26+
27+
private boolean dfs(Graph G, Vertex<T> V, HashSet<Vertex<T>> set) {
28+
set.add(V);
29+
for (Vertex<T> v : V.adjacent) {
30+
if (!set.contains(v)) return dfs(G, v, set);
31+
else return true;
32+
}
33+
return false;
34+
}
35+
36+
class Vertex<T> {
37+
T value;
38+
List<Vertex<T>> adjacent;
39+
}
40+
41+
class Graph {
42+
List<Vertex> vertices;
43+
List<Edge> edges;
44+
}
45+
46+
class Edge {
47+
Vertex src;
48+
Vertex dest;
49+
}
50+
}

0 commit comments

Comments
 (0)