fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideoenb
  9. {
  10. public static Stack stack = new Stack();
  11. public static void main (String[] args) throws java.lang.Exception
  12. {
  13. // create some input
  14. Node head = new Node(1);
  15. head.left = new Node(2);
  16. head.right = new Node(3);
  17. head.right.left = new Node(4);
  18.  
  19. iterativeInorder(head);
  20. }
  21.  
  22. static void iterativeInorder(Node head)
  23. {
  24. Node current = head;
  25. while( current != null )
  26. {
  27.  
  28. if( current.left != null && current.left.visited == false)
  29. {
  30. stack.push( current );
  31. current = current.left;
  32. continue;
  33. }
  34. else
  35. {
  36. visit(current);
  37. current.visited = true;
  38. }
  39.  
  40. if( current.right != null )
  41. {
  42. current = current.right;
  43. }
  44. else
  45. {
  46. if( ! stack.empty() )
  47. {
  48. current = (Node) stack.pop();
  49. }
  50. else
  51. {
  52. current = null;
  53. }
  54.  
  55. }
  56.  
  57. }
  58. }
  59.  
  60. static void visit(Node current)
  61. {
  62. System.out.println(current.value+"\n");
  63. }
  64. }
  65.  
  66. class Node
  67. {
  68. public Node left=null;
  69. public int value;
  70. public boolean visited=false;
  71. public Node right=null;
  72.  
  73. public Node(int value)
  74. {
  75. this.value = value;
  76. }
  77. }
Success #stdin #stdout 0.1s 320256KB
stdin
Standard input is empty
stdout
2

1

4

3