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