12
12
/**
13
13
* Breadth-First Search implementation for tree/graph traversal.
14
14
* @author caos321
15
- * @co-author manishraj27
15
+ * @co-author @ manishraj27
16
16
* @see <a href="https://en.wikipedia.org/wiki/Breadth-first_search">Breadth-first search</a>
17
17
*/
18
18
public class BreadthFirstSearch <T > {
19
-
20
19
private final List <T > visited = new ArrayList <>();
21
20
private final Set <T > visitedSet = new HashSet <>();
22
21
@@ -28,46 +27,30 @@ public class BreadthFirstSearch<T> {
28
27
* @return Optional containing the found node, or empty if not found
29
28
*/
30
29
public Optional <Node <T >> search (final Node <T > root , final T value ) {
31
- // Handle null root
32
30
if (root == null ) {
33
31
return Optional .empty ();
34
32
}
35
33
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 ());
45
36
46
- // Check root node
47
- if (value .equals (root .getValue ())) {
48
- visited .add (root .getValue ());
37
+ if (root .getValue () == value ) {
49
38
return Optional .of (root );
50
39
}
51
40
52
- // Add root to visited
53
- visited .add (root .getValue ());
54
- visitedSet .add (root .getValue ());
55
-
56
- // Process remaining nodes
57
41
Queue <Node <T >> queue = new ArrayDeque <>(root .getChildren ());
58
42
while (!queue .isEmpty ()) {
59
43
final Node <T > current = queue .poll ();
60
44
T currentValue = current .getValue ();
61
-
62
- // Skip if already visited
45
+
63
46
if (visitedSet .contains (currentValue )) {
64
47
continue ;
65
48
}
66
49
67
50
visited .add (currentValue );
68
51
visitedSet .add (currentValue );
69
52
70
- if (value .equals (currentValue )) {
53
+ if (currentValue == value || ( value != null && value .equals (currentValue ) )) {
71
54
return Optional .of (current );
72
55
}
73
56
0 commit comments