dfs iterative tree code example

Example: 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;
        }
      }
    }

}

Tags:

Java Example