Print out all of its root-to-leaf paths of a binary tree .

Paths for below tree are :

A – B – D

A – C – E

Algorithm :

initialize: pathlen = 0, path[500] //500 for max length of tree path 

/*printPaths traverses nodes of tree in preorder */

printPaths(tree, path[], pathlen)
   1) If node is not NULL then
         a) push data to path array:
                path[pathlen] = node->data.
         b) increment pathlen
   2) If node is a leaf node then print the path array.
   3) Else
        a) Call printPaths for left subtree
                 printPaths(node->left, path, pathLen)
        b) Call printPaths for right subtree.
                printPaths(node->right, path, pathLen)

Code :

void printPaths(struct node* node)
  int path[500];
  printPathsRecur(node, path, 0);

void printArray(int ints[], int len)
  int i;
  for (i=0; i<len; i++) {
    printf("%d ", ints[i]);
/* Recursive  function --  */
void printPathsByRecur(struct node* node, int path[], int pathLen)
  if (node==NULL) return;
  /* append this node to the path array */
  path[pathLen] = node->data;
  /* it's a leaf, so print the path that led to here */
  if (node->left==NULL && node->right==NULL)
    printArray(path, pathLen);
    printPathsByRecur(node->left, path, pathLen);
    printPathsByRecur(node->right, path, pathLen);

Leave a Reply

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

For Inserting code :
Paste your code in the comment form, select it and then click the language link

C | C++ | Java |