Iterative Preorder Traversal | Java program to implement iterative preorder traversal ; A binary tree node ; An iterative process to print preorder traversal of Binary tree ; Base Case ; Create an empty stack and push root to it ; Pop all items one by one . Do following for every popped item a ) print it b ) push its right child c ) push its left child Note that right child is pushed first so that left is processed first ; Pop the top item from stack and print it ; Push right and left children of the popped node to stack ; driver program to test above functions
import java . util . Stack ; class Node { int data ; Node left , right ; Node ( int item ) { data = item ; left = right = null ; } } class BinaryTree { Node root ; void iterativePreorder ( ) { iterativePreorder ( root ) ; } void iterativePreorder ( Node node ) { if ( node == null ) { return ; } Stack < Node > nodeStack = new Stack < Node > ( ) ; nodeStack . push ( root ) ; while ( nodeStack . empty ( ) == false ) { Node mynode = nodeStack . peek ( ) ; System . out . print ( mynode . data + " ▁ " ) ; nodeStack . pop ( ) ; if ( mynode . right != null ) { nodeStack . push ( mynode . right ) ; } if ( mynode . left != null ) { nodeStack . push ( mynode . left ) ; } } } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 10 ) ; tree . root . left = new Node ( 8 ) ; tree . root . right = new Node ( 2 ) ; tree . root . left . left = new Node ( 3 ) ; tree . root . left . right = new Node ( 5 ) ; tree . root . right . left = new Node ( 2 ) ; tree . iterativePreorder ( ) ; } }