fork download
  1.  
  2. import java.util.LinkedList;
  3. /**
  4.  * Node Structure
  5.  * @author Prateek
  6.  *
  7.  */
  8. class Node {
  9. public Node left;
  10. public int data;
  11. public Node right;
  12.  
  13. public Node(int val) {
  14. this.data = val;
  15. }
  16.  
  17. @Override
  18. public String toString() {
  19. return this.data + "";
  20. }
  21. }
  22. /**
  23.  * Level order Traversal of Tree (Using Queue)
  24.  * @author Prateek
  25.  */
  26. class LevelOrder {
  27.  
  28. public void printLevelOrder(Node root){
  29. if(root==null)
  30. return ;
  31.  
  32. LinkedList<Node> queue = new LinkedList<Node>();
  33. queue.addLast(root);
  34. queue.addLast(null);
  35.  
  36. while(!queue.isEmpty()){
  37. Node poped = queue.removeFirst(); //dequeue
  38.  
  39. if (poped == null) {
  40. if(queue.isEmpty()) // if last node , terminate
  41. continue;
  42. queue.addLast(null);
  43. System.out.println();
  44. }
  45. else {
  46.  
  47. System.out.print(poped.data + "\t");
  48.  
  49. if (poped.left != null)
  50. queue.addLast(poped.left);
  51. if (poped.right != null)
  52. queue.addLast(poped.right);
  53. }
  54. }
  55. }
  56.  
  57. public static void main(String[] args) {
  58. Node root = new Node(1);
  59. root.left = new Node(2);
  60. root.left.left = new Node(4);
  61. root.left.right = new Node(5);
  62. root.left.right.left = new Node(8);
  63. root.left.right.right = new Node(9);
  64. root.left.right.left.left = new Node(10);
  65.  
  66. root.right = new Node(3);
  67. root.right.left = new Node(6);
  68. root.right.right = new Node(7);
  69.  
  70. LevelOrder obj = new LevelOrder();
  71. obj.printLevelOrder(root);
  72. }
  73. }
  74.  
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
1	
2	3	
4	5	6	7	
8	9	
10