Node
class and its methods.
Example:
apple
/ \
banana mango
/ \ / Find
peach strawberry
\ /
cherry
cherry ==> True
adjacent nodes
before searching its second level adjacent nodes
. The best iterative approach would be to use a Queue
to keep a track of the visited nodes
.
A feasible approach is to use a Queue
to traverse through the nodes in order to search for the data :
1. If the input
is null
or the root node
is null
, return false.
2. Declare and initialize a Queue
object, which can store objects of the type Node
.
3. Add the root node
to the Queue
and mark it's visited
property to true.
4. Start the first loop
to run till the Queue
becomes empty
.
5. Within the loop
, poll
an object from the Queue. Check its data and if it is equal to the input data, return true
.
6. Else, traverse through all its adjacent nodes using a second inner loop
, mark its visited property to true and add them to the Queue
.
7. Outside the first loop
,return false
, which indicates that the data was not found in the graph
.
public boolean breadthFirstSearch(Node rootNode, String data){ }
C
Java
Python