forked from lemonbashar/java-algo-expert
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFS.java
More file actions
60 lines (51 loc) · 1.42 KB
/
DFS.java
File metadata and controls
60 lines (51 loc) · 1.42 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
package algoexpert;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
/*
Problem:
Implement DFS for Tree
DFS - O(v + e)
1. Recursion
2. Stack
*/
public class DFS {
static class Node{
String name;
ArrayList<Node> children = new ArrayList<Node>();
public Node(String name) {
this.name = name;
}
public Node addChild(String name) {
Node child = new Node(name);
children.add(child);
return this;
}
// implementation part begins
// --------------------------
public ArrayList<String> useRecursion(ArrayList<String> array) {
array.add(this.name);
for (Node child : children){
child.useRecursion(array);
}
return array;
}
public ArrayList<String> useStack(ArrayList<String> array) {
Queue<Node> queue = new LinkedList<>();
queue.add(this);
while(!queue.isEmpty()) {
Node current = queue.poll();
array.add(current.name);
for (Node child : current.children) {
queue.add(child);
}
}
return array;
}
public ArrayList<String> depthFirstSearch(ArrayList<String> array)
{
return this.useRecursion(array);
}
}
}