You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Well, Depth First Search, also known as DFS is a way to traverse the Binary Search Tree or a graph. The fundamental idea of DFS lies within its name. We search the depth first.
For example, consider the below image.
Suppose we start from Node A. First we will go to its left, so we meet node B. Now we go to the left of B and meet Node E. Now we go to left of Node E and meet no one so we return to Node E. Now we go to the right of Node E and meet no one and return back. We are done exploring Node E so we return back to B. Now we move on to the right of B and meet Node F. We do the same with Node F ie first go left and then right and return back to B. Now we have explored Node B completely so we return back to A. Now we go to the next child of Node A i.e Node C. We go to the left of Node C and find Node F. But Node F is already visited once so we will come back again without printing it. We go to the right of C and find no one so we return. We are done exploring C so we return back to A. We do the exact same process for Node D and return back to Node A in the end.
So as you can notice we are exploring the depth of a particular node first. We go deeper and deeper in one direction of the node and visit all the nodes in this fashion. DFS is an efficient way of traversing a tree and it can be performed by writing a recursive code. The code has been attatched in the code file.