fork download
  1. /**
  2.  * Prints out all root to leaf nodes
  3.  * @author Prateek
  4.  */
  5. class Root2Leaf {
  6. private static final int size=10;
  7. /**
  8. * Subroutine to print all paths from root to leaves
  9. * @param list: holds the nodes encountered, values are overriden based on the value of index
  10. * @param index
  11. */
  12. private void printRoot2LeafPaths(Node root,Node[] list, int index) {
  13.  
  14. if(root==null)
  15. return ;
  16.  
  17. list[index++]=root;
  18.  
  19. if(root.left==null && root.right==null)
  20. {
  21. for(int i=0;i<index;i++)
  22. System.out.print(list[i]+"-->\t");
  23. System.out.println();
  24. }
  25. printRoot2LeafPaths(root.left,list,index);
  26. printRoot2LeafPaths(root.right,list,index);
  27.  
  28. return;
  29. }
  30.  
  31. public static void main(String[] args) {
  32. /*Node root = new Node(1) ;
  33. root.left= new Node(2) ;
  34. root.right= new Node(3) ;
  35. root.left.left= new Node(4) ;
  36. root.left.right= new Node(5) ;
  37. root.right.left= new Node(6) ;
  38. root.right.right= new Node(7) ;
  39. root.left.right.left= new Node(8) ;
  40. root.left.right.right= new Node(9) ;
  41. root.left.right.left.right= new Node(10) ; */
  42.  
  43. Node root = new Node(1) ;
  44. root.left= new Node(2) ;
  45. root.right= new Node(3) ;
  46. root.left.left= new Node(4) ;
  47. root.left.right= new Node(5) ;
  48. root.right.left= new Node(6) ;
  49. root.right.right= new Node(7) ;
  50.  
  51.  
  52. root.left.left.right= new Node(8) ;
  53. root.left.left.right.left= new Node(9) ;
  54.  
  55. Root2Leaf obj= new Root2Leaf();
  56. Node[] list = new Node[size];
  57. obj.printRoot2LeafPaths(root,list,0);
  58. }
  59. }
  60.  
  61. class Node{
  62. public Node left;
  63. public int data;
  64. public Node right;
  65.  
  66. public Node(int val) {
  67. this.data=val;
  68. }
  69.  
  70. @Override
  71. public String toString(){
  72. return this.data + "";
  73. }
  74. }
  75.  
Success #stdin #stdout 0.07s 380160KB
stdin
Standard input is empty
stdout
1-->	2-->	4-->	8-->	9-->	
1-->	2-->	5-->	
1-->	3-->	6-->	
1-->	3-->	7-->