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