Advertisement
alvsjo

bst pre/post order

May 26th, 2017
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.74 KB | None | 0 0
  1. void iterativePreorder()
  2.     {
  3.         iterativePreorder(root);
  4.     }
  5.  
  6.     // An iterative process to print preorder traversal of Binary tree
  7.     void iterativePreorder(Node node) {
  8.          
  9.         // Base Case
  10.         if (node == null) {
  11.             return;
  12.         }
  13.  
  14.         // Create an empty stack and push root to it
  15.         Stack<Node> nodeStack = new Stack<Node>();
  16.         nodeStack.push(root);
  17.  
  18.         /* Pop all items one by one. Do following for every popped item
  19.          a) print it
  20.          b) push its right child
  21.          c) push its left child
  22.          Note that right child is pushed first so that left is processed first */
  23.         while (nodeStack.empty() == false) {
  24.              
  25.             // Pop the top item from stack and print it
  26.             Node mynode = nodeStack.peek();
  27.             System.out.println(mynode.info);
  28.             nodeStack.pop();
  29.  
  30.             // Push right and left children of the popped node to stack
  31.             if (mynode.right != null) {
  32.                 nodeStack.push(mynode.right);
  33.             }
  34.             if (mynode.left != null) {
  35.                 nodeStack.push(mynode.left);
  36.             }
  37.         }
  38.     }
  39.    
  40.     void itPost()
  41.     {
  42.         if (root==null) return;
  43.        
  44.         Stack<Node> s1= new Stack<>();
  45.         Stack<Node> s2= new Stack<>();
  46.  
  47.         s1.push(root);
  48.        
  49.         while(!s1.isEmpty())
  50.         {
  51.             Node temp=s1.pop();
  52.             s2.push(temp);
  53.            
  54.             if (temp.left != null) {
  55.                 s1.push(temp.left);
  56.             }
  57.             if (temp.right != null) {
  58.                 s1.push(temp.right);
  59.             }
  60.         }
  61.         while(!s2.isEmpty())
  62.         {
  63.             Node temp=s2.pop();
  64.             System.out.println(temp.info);
  65.         }
  66.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement