Depth first search

Depth first search, or DFS, is a search technique where we start searching from a node and go as deep as possible to the node from the target node through the branches. DFS is different from BFS, and we try to dig deeper instead of spreading out first. DFS grows vertically and backtracks when it reaches the end of the branch and moves the next available adjacent nodes until the search is over. We can take the same tree image from the last section, which is shown as follows:

If we apply DFS here, the traversal will be . We start from the root and then visit the first child, which is 3. However, instead of going to 10 like the BFS, we will explore the child nodes of 3 and do this repeatedly until we reach the bottom of the branch. In BFS, we had taken the iterative approach. For DFS, we will take the recursive approach. Let's now write the pseudocode for DFS:

procedure DFS(Node current)       
for each node v that is childnode of current
DFS(v)
end for each
end procedure
..................Content has been hidden....................

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