-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeavesOfSubtree.java
More file actions
66 lines (57 loc) · 1.65 KB
/
LeavesOfSubtree.java
File metadata and controls
66 lines (57 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import java.util.LinkedList;
class Graph {
LinkedList<Integer>[] vertices;
boolean[] visited;
int v;
Graph(int v) {
this.vertices = new LinkedList[v];
this.v = v;
for (int i = 0; i < v; i++)
this.vertices[i] = new LinkedList<>();
this.visited = new boolean[v];
}
public void addEdge(int v1, int v2) {
this.vertices[v1].add(v2);
this.vertices[v2].add(v1);
}
public void printGraph() {
for (int i = 0; i < this.v; i++) {
System.out.println("Adjacency list of vertex " + i);
System.out.print("head");
for (Integer j : this.vertices[i]) {
System.out.print(" -> " + j);
}
System.out.println("\n");
}
}
private void dfsRecursive(int vertex) {
// System.out.println(vertex);
this.visited[vertex] = true;
if(this.vertices[vertex].size()==1)
System.out.println(vertex);
for (int i = 0; i < this.vertices[vertex].size(); i++) {
int v = this.vertices[vertex].get(i);
if (!this.visited[v])
dfsRecursive(v);
}
}
public void leaves(int subtreeNode) {
dfsRecursive(subtreeNode);
}
}
public class LeavesOfSubtree {
public static void main(String[] args) {
Graph obj = new Graph(10);
obj.addEdge(0, 1);
obj.addEdge(0, 6);
obj.addEdge(1, 2);
obj.addEdge(1, 3);
obj.addEdge(1, 4);
obj.addEdge(3, 5);
obj.addEdge(6, 7);
obj.addEdge(6, 8);
obj.addEdge(6, 9);
obj.leaves(1);
// obj.printGraph();
}
}