Breadth first search

In a tree structure, a root is connected to its child node, and each child node can be represented as a tree. We have already seen this in Chapter 6, Understanding and Implementing Trees. In a breadth first search, popularly known as BFS, we start from a node (mostly root node) and first visit all adjacent or neighbor nodes before visiting the other neighbor nodes. In other words, we have to move level by level while we are applying BFS. As we search level by level, this technique is known as breadth first search. In the following tree structure, we can use BFS:

For this tree, the BFS will follow the nodes like this: 

The pseudocode of BFS will look like this:

procedure BFS(Node root)  
Q := empty queue
Q.enqueue(root);

while(Q != empty)
u := Q.dequeue()

for each node w that is childnode of u
Q.enqueue(w)
end for each
end while
end procedure

We can see that we have kept one queue for tracking which nodes we need to visit. We can keep another queue to hold the sequence of visits and return it to show the visit sequence. Now, we will implement the BFS using PHP 7.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset