fork(1) download
  1.  
  2. import java.util.Stack;
  3.  
  4. /**
  5.  * Iterative Post Order Traversal using two stacks
  6.  * @author PRATEEK
  7.  */
  8. class IterativePostOrderDoubleStack {
  9.  
  10. public static void main(String[] args) {
  11. Node root = new Node(12);
  12. root.left = new Node(8);
  13. root.left.left = new Node(6);
  14. root.left.right = new Node(10);
  15.  
  16. root.right = new Node(16);
  17. root.right.left = new Node(14);
  18. root.right.right = new Node(20);
  19.  
  20. IterativePostOrderDoubleStack obj = new IterativePostOrderDoubleStack();
  21. obj.iterativePostOrder(root);
  22. }
  23.  
  24. /**
  25. * Iterative Pre-order traversal using two stacks
  26. */
  27. public void iterativePostOrder(Node root)
  28. {
  29. Stack<Node> processed = new Stack<Node>();
  30. Stack<Node> current = new Stack<Node>();
  31.  
  32. current.push(root);
  33. while(!current.isEmpty())
  34. {
  35. Node item = current.pop();
  36. processed.push(item);
  37.  
  38. if(item.left!=null)
  39. current.push(item.left);
  40. if(item.right!=null)
  41. current.push(item.right);
  42.  
  43. }
  44. while(!processed.isEmpty())
  45. {
  46. System.out.print(processed.pop() + "\t");
  47. }
  48. }
  49. }
  50. //-------------------------------------
  51. class Node implements Comparable<Node> {
  52. public Node left;
  53. public int data;
  54. public Node right;
  55.  
  56. public Node(int val)
  57. {
  58. this.data=val;
  59. }
  60.  
  61. @Override
  62. public int compareTo(Node that) {
  63. return this.data - that.data ;
  64. }
  65.  
  66. @Override
  67. public String toString(){
  68. return this.data + "";
  69. }
  70. }
  71.  
  72.  
Success #stdin #stdout 0.06s 380224KB
stdin
Standard input is empty
stdout
6	10	8	14	20	16	12