iterative depth first traversal code example
Example 1: iterative dfs in tree
import java.util.Stack;
class Node
{
int data;
Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
@SuppressWarnings("unchecked")
class BinaryTree
{
Node root;
public static void inOrderTraversal(Node root)
{
Stack<Node> stack = new Stack();
Node curr = root;
while (!stack.empty() || curr != null)
{
if (curr != null)
{
stack.push(curr);
curr = curr.left;
}
else
{
curr = stack.pop();
System.out.print(curr.data + " ");
curr = curr.right;
}
}
}
}
Example 2: depth first search stack
DFS-iterative (G, s):
let S be stack
S.push( s )
mark s as visited.
while ( S is not empty):
v = S.top( )
S.pop( )
for all neighbours w of v in Graph G:
if w is not visited :
S.push( w )
mark w as visited
DFS-recursive(G, s):
mark s as visited
for all neighbours w of s in Graph G:
if w is not visited:
DFS-recursive(G, w)