Iterative Preorder Traversal | C # 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 Code
using System ; using System . Collections . Generic ; public class Node { public int data ; public Node left , right ; public Node ( int item ) { data = item ; left = right = null ; } } class GFG { public Node root ; public virtual void iterativePreorder ( ) { iterativePreorder ( root ) ; } public virtual void iterativePreorder ( Node node ) { if ( node == null ) { return ; } Stack < Node > nodeStack = new Stack < Node > ( ) ; nodeStack . Push ( root ) ; while ( nodeStack . Count > 0 ) { Node mynode = nodeStack . Peek ( ) ; Console . Write ( 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 ) { GFG tree = new GFG ( ) ; 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 ( ) ; } }