Skip to content

Commit 18267b6

Browse files
authored
Fixede clear() calls
1 parent 02e49e7 commit 18267b6

File tree

1 file changed

+36
-17
lines changed

1 file changed

+36
-17
lines changed

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

Lines changed: 36 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -28,42 +28,61 @@ public class BreadthFirstSearch<T> {
2828
* @return Optional containing the found node, or empty if not found
2929
*/
3030
public Optional<Node<T>> search(final Node<T> root, final T value) {
31-
if (value == null || root == null) {
31+
// Handle null root
32+
if (root == null) {
3233
return Optional.empty();
3334
}
3435

35-
visited.clear();
36-
visitedSet.clear();
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+
}
3745

38-
Queue<Node<T>> queue = new ArrayDeque<>();
39-
queue.offer(root);
40-
visitedSet.add(root.getValue());
46+
// Check root node
47+
if (value.equals(root.getValue())) {
48+
visited.add(root.getValue());
49+
return Optional.of(root);
50+
}
51+
52+
// Add root to visited
4153
visited.add(root.getValue());
54+
visitedSet.add(root.getValue());
4255

56+
// Process remaining nodes
57+
Queue<Node<T>> queue = new ArrayDeque<>(root.getChildren());
4358
while (!queue.isEmpty()) {
4459
final Node<T> current = queue.poll();
60+
T currentValue = current.getValue();
61+
62+
// Skip if already visited
63+
if (visitedSet.contains(currentValue)) {
64+
continue;
65+
}
66+
67+
visited.add(currentValue);
68+
visitedSet.add(currentValue);
4569

46-
if (value.equals(current.getValue())) {
70+
if (value.equals(currentValue)) {
4771
return Optional.of(current);
4872
}
4973

50-
for (Node<T> child : current.getChildren()) {
51-
if (child != null && !visitedSet.contains(child.getValue())) {
52-
queue.offer(child);
53-
visitedSet.add(child.getValue());
54-
visited.add(child.getValue());
55-
}
56-
}
74+
queue.addAll(current.getChildren());
5775
}
76+
5877
return Optional.empty();
5978
}
6079

6180
/**
6281
* Returns the list of nodes in the order they were visited.
6382
*
64-
* @return A new list containing the visited nodes
83+
* @return List containing the visited nodes
6584
*/
6685
public List<T> getVisited() {
67-
return new ArrayList<>(visited);
86+
return visited;
6887
}
69-
}
88+
}

0 commit comments

Comments
 (0)