Wednesday, June 25, 2014

Print all path from its root to leaf Node in one per line



Algorithm:
Initialize: array of size equal to height of BT. let say arr[height()]
/*height of tree is equal to max number of levels in tree*/
Call Method with signature:
  int[] arr = new int[height()];
  printAllPath(root, arr, 0);
/*printPathsRecur traverses nodes of tree in preorder */
printPathsRecur(tree, path[], level)
1) If node is null then return;
push data to path array: arr[level] = node->data.
2) If node is a leaf node then print the path array. return;
3)   a) Call printPathsRecur for left subtree
                 printPathsRecur(node->left, path, level+1)
     b) Call printPathsRecur for right subtree.
                printPathsRecur(node->right, path, level+1)

Example:

 static void printAllPath(Node root, int[] arr, int level){
  
  if(root == null) return;
  
  arr[level] = root.data;
  
  if(root.left == null && root.right == null)
  {
   printPath(arr, 0, level);
   return;
  }
  
  printAllPath(root.left, arr, level+1);
  printAllPath(root.right, arr, level+1);
  
 }


 private static void printPath(int[] arr, int l, int level) {

  for(int i = l; i <= level; i++)
   System.out.print(arr[i]+", ");
  System.out.println();
  
 }



No comments:

Post a Comment