forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDepthFirstSearch.java
More file actions
32 lines (26 loc) · 860 Bytes
/
DepthFirstSearch.java
File metadata and controls
32 lines (26 loc) · 860 Bytes
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
package com.thealgorithms.searches;
import com.thealgorithms.datastructures.Node;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* @author: caos321
* @date: 31 October 2021 (Sunday)
* @wiki: https://en.wikipedia.org/wiki/Depth-first_search
*/
public class DepthFirstSearch<T> {
private final List<T> visited = new ArrayList<>();
public Optional<Node<T>> recursiveSearch(final Node<T> node, final Integer value) {
if (node == null) {
return Optional.empty();
}
visited.add(node.getValue());
if (node.getValue().equals(value)) {
return Optional.of(node);
}
return node.getChildren().stream().map(v -> recursiveSearch(v, value)).flatMap(Optional::stream).findAny();
}
public List<T> getVisited() {
return visited;
}
}