I am bit confused after reading examples at DFS where output is printed in different fashion for both DFS approaches though both are said to be DFS.
In fact DFS recursion approach print the output just in same fashion as BFS. Then what's the difference ? Is recursion approach given here not an example of DFS ?
Using Stack
// Iterative DFS using stack
public void dfsUsingStack(Node node)
{
Stack<Node> stack=new Stack<Node>();
stack.add(node);
node.visited=true;
while (!stack.isEmpty())
{
Node element=stack.pop();
System.out.print(element.data + " ");
List<Node> neighbours=element.getNeighbours();
for (int i = 0; i < neighbours.size(); i++) {
Node n=neighbours.get(i);
if(n!=null && !n.visited)
{
stack.add(n);
n.visited=true;
}
}
}
}
Output is 40,20,50,70,60,30,10
Recursion Approach
// Recursive DFS
public void dfs(Node node)
{
System.out.print(node.data + " ");
List neighbours=node.getNeighbours();
node.visited=true;
for (int i = 0; i < neighbours.size(); i++) {
Node n=neighbours.get(i);
if(n!=null && !n.visited)
{
dfs(n);
}
}
}
output is 40,10,20,30,60,50,70 which is same as output under BFS
So what's the difference ?