@@ -28,42 +28,61 @@ public class BreadthFirstSearch<T> {
28
28
* @return Optional containing the found node, or empty if not found
29
29
*/
30
30
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 ) {
32
33
return Optional .empty ();
33
34
}
34
35
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
+ }
37
45
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
41
53
visited .add (root .getValue ());
54
+ visitedSet .add (root .getValue ());
42
55
56
+ // Process remaining nodes
57
+ Queue <Node <T >> queue = new ArrayDeque <>(root .getChildren ());
43
58
while (!queue .isEmpty ()) {
44
59
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 );
45
69
46
- if (value .equals (current . getValue () )) {
70
+ if (value .equals (currentValue )) {
47
71
return Optional .of (current );
48
72
}
49
73
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 ());
57
75
}
76
+
58
77
return Optional .empty ();
59
78
}
60
79
61
80
/**
62
81
* Returns the list of nodes in the order they were visited.
63
82
*
64
- * @return A new list containing the visited nodes
83
+ * @return List containing the visited nodes
65
84
*/
66
85
public List <T > getVisited () {
67
- return new ArrayList <>( visited ) ;
86
+ return visited ;
68
87
}
69
- }
88
+ }
0 commit comments