This is the second post in the series of tree/graph traversal. As in the last post breadth first search I used a concrete example with sample code in Java to explain the traversal algorithm. So without further a due here is the java code for depth first search (dfs)

public void depthFirstTraversal(Node rootNode) {
Stack s = new Stack();
s.add(rootNode);
rootNode.visited = true;
while(!s.isEmpty()){
Node n = s.pop();
System.out.print(n.data + " ");
for(Node adj : n.adjacentNodes){
if(!adj.visited){
adj.visited = true;
s.push(adj);
}
}
}
}

As opposed to breadth first traversal, depth first traversal uses stack to push the newly expanded node instead of Queue. For further reference read this

### Like this:

Like Loading...

Awesome thanks for the info

Good day! I just would like to give an enormous thumbs up for the great data you’ve gotten here on this post.

I can be coming back to your weblog for extra soon.