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