I have the following implementation of a Depth First Search algorithm:
public static void printDFS(Node root) {
Stack<Node> stack = new Stack<Node>();
stack.push(root);
while(!stack.isEmpty()) {
Node curr = stack.pop();
System.out.println(curr.getValue()) ;
if (curr.getLeft() != null) {
stack.push(curr.getLeft());
}
if (curr.getRight() != null) {
stack.push(curr.getRight());
}
}
}
and when I run it on a tree that looks like this:
0
/ \
6 7
/ \ / \
5 4 3 2
I get the visited output as: 0 -> 7 -> 2 -> 3 -> 6 -> 4 -> 5
Is this a 'correct' DFS ordering? I would have expected the output to have been a pre-order traversal (ie 0 ->6 -> 5 -> 4 -> 7 -> 3 -> 2) and I know I can get this by first pushing the right node of each subtree. But what I want to know is what is the correct visitation order in a DFS algorithm?