Skip to content

Commit c7d4af5

Browse files
authored
Fixed test cases
1 parent 18267b6 commit c7d4af5

File tree

1 file changed

+6
-23
lines changed

1 file changed

+6
-23
lines changed

src/main/java/com/thealgorithms/searches/BreadthFirstSearch.java

Lines changed: 6 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,10 @@
1212
/**
1313
* Breadth-First Search implementation for tree/graph traversal.
1414
* @author caos321
15-
* @co-author manishraj27
15+
* @co-author @manishraj27
1616
* @see <a href="https://en.wikipedia.org/wiki/Breadth-first_search">Breadth-first search</a>
1717
*/
1818
public class BreadthFirstSearch<T> {
19-
2019
private final List<T> visited = new ArrayList<>();
2120
private final Set<T> visitedSet = new HashSet<>();
2221

@@ -28,46 +27,30 @@ public class BreadthFirstSearch<T> {
2827
* @return Optional containing the found node, or empty if not found
2928
*/
3029
public Optional<Node<T>> search(final Node<T> root, final T value) {
31-
// Handle null root
3230
if (root == null) {
3331
return Optional.empty();
3432
}
3533

36-
// Check root value first
37-
if (value == null) {
38-
if (root.getValue() == null) {
39-
visited.add(null);
40-
return Optional.of(root);
41-
}
42-
visited.add(root.getValue());
43-
return Optional.empty();
44-
}
34+
visited.add(root.getValue());
35+
visitedSet.add(root.getValue());
4536

46-
// Check root node
47-
if (value.equals(root.getValue())) {
48-
visited.add(root.getValue());
37+
if (root.getValue() == value) {
4938
return Optional.of(root);
5039
}
5140

52-
// Add root to visited
53-
visited.add(root.getValue());
54-
visitedSet.add(root.getValue());
55-
56-
// Process remaining nodes
5741
Queue<Node<T>> queue = new ArrayDeque<>(root.getChildren());
5842
while (!queue.isEmpty()) {
5943
final Node<T> current = queue.poll();
6044
T currentValue = current.getValue();
61-
62-
// Skip if already visited
45+
6346
if (visitedSet.contains(currentValue)) {
6447
continue;
6548
}
6649

6750
visited.add(currentValue);
6851
visitedSet.add(currentValue);
6952

70-
if (value.equals(currentValue)) {
53+
if (currentValue == value || (value != null && value.equals(currentValue))) {
7154
return Optional.of(current);
7255
}
7356

0 commit comments

Comments
 (0)