21 Dec 2013

All Root to Leaf paths

Problem Statement:
          Print out all Root to Leaf paths in the given Binary Tree
Fig: Given Binary Tree
Output:
1-->    2-->    4-->    8-->    9-->    
1-->    2-->    5-->    
1-->    3-->    6-->    
1-->    3-->    7-->    

Solution:
Full Source Code: LINK

Implementation Logic below :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
       /**
  * Subroutine to print all paths from root to leaves 
  * @param list: holds the nodes encountered, values are overriden based on the value of index
  * @param index
  */
 private void printRoot2LeafPaths(Node root,Node[] list, int index) {

  if(root==null)
   return  ;

  list[index++]=root;

  if(root.left==null && root.right==null)
  {
   for(int i=0;i<index;i++)
    System.out.print(list[i]+"-->\t");
   System.out.println();
  }
  printRoot2LeafPaths(root.left,list,index);
  printRoot2LeafPaths(root.right,list,index);

  return;
 }

Please comment and post your suggestions if any.
Happy Coding !! :)

No comments:

Post a Comment