fork download
  1. class Node {
  2. public Node left;
  3. public int data;
  4. public Node right;
  5. //Test
  6. public Node(int val) {
  7. this.data=val;
  8. }
  9. }
  10.  
  11.  
  12. /**
  13.  * BFS of Tree
  14.  * @author Prateek
  15.  */
  16. class PrintTreeBFS {
  17.  
  18. /**
  19. * for printing BFS (recursive)
  20. * @param root
  21. */
  22. public void printTreeBFS(Node root) {
  23. if(root==null)
  24. System.out.println("Empty Tree");
  25.  
  26. int height=height(root);
  27.  
  28. for(int i=1 ; i<=height ; i++){
  29. printLevel(root, i);
  30. System.out.println();
  31. }
  32. }
  33.  
  34. /**
  35. * Prints nodes at a given level
  36. * @param root
  37. * @param level
  38. */
  39. public void printLevel(Node root, int level) {
  40. if(root==null)
  41. return ;
  42.  
  43. if(level==1)
  44. System.out.print(root.data + "\t");
  45.  
  46. printLevel(root.left, level-1) ;
  47. printLevel(root.right, level-1) ;
  48. }
  49.  
  50. /**
  51. * @param root of the tree
  52. * @return height of the tree
  53. */
  54. public int height(Node root) {
  55. if(root == null)
  56. return 0;
  57.  
  58. int lHeight=height(root.left);
  59. int rHeight=height(root.right);
  60.  
  61. return max(lHeight,rHeight) + 1;
  62. }
  63.  
  64. /**
  65. * @param val1
  66. * @param val2
  67. * @return maximum val
  68. */
  69. private int max(int val1, int val2) {
  70. return val1 > val2 ? val1 : val2;
  71. }
  72.  
  73.  
  74. public static void main(String[] args) {
  75. Node root=new Node(12);
  76.  
  77. Node n1=new Node(14);
  78. Node n2=new Node(18);
  79. Node n3=new Node(10);
  80. root.left=new Node(8);
  81. root.right=new Node(16);
  82. root.left.left=new Node(6);
  83. root.left.right=n3;
  84. root.right.left=n1;
  85. root.right.right=n2;
  86.  
  87.  
  88. PrintTreeBFS obj=new PrintTreeBFS();
  89. obj.printTreeBFS(root);
  90.  
  91. }
  92. }
  93.  
Success #stdin #stdout 0.08s 380160KB
stdin
Standard input is empty
stdout
12	
8	16	
6	10	14	18