Print all root to leaf paths in a tree

Given a binary tree,Print all root to leaf paths in it.
Binary Tree
root to leaf paths in above tree.

[1 2 4]
[1 3 5]
[1 3 6]

We start with the root and while traversing the tree we keep storing node data in array.We print the array when we reach a leaf node.

struct node
{
   int data;
   struct node* left;
   struct node* right;
};

void printRootToLeafPath(struct node* node)
{
  int path[100];
  printRootToLeafPathUtil(node, path, 0);
}

void printRootToLeafPathUtil(struct node* node, int path[], int pathLen)
{
  if (node==NULL)
    return;

  path[pathLen] = node->data;
  pathLen++;

  if (node->left==NULL && node->right==NULL)
  {
    printArray(path, pathLen);
  }
  else
  {
    printRootToLeafPathUtil(node->left, path, pathLen);
    printRootToLeafPathUtil(node->right, path, pathLen);
  }
}

void printArray(int arr[], int n)
{
  for (int i=0; i<n; i++)
  {
    printf("%d ", arr[i]);
  }
  printf("\n");
}

Time Complexity : O(n)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation