Description: Given a tree, print all paths from the root to various leaf nodes.

 
If video does not load, Click here
 
Example:
 

In the figure below, various root-to-leaf paths:

8-5

8-3-2

8-3-1

 
Algorithm and Implementation:

 

Consider the following function ‘printpath’ to solve the problem:

 

/*The array ‘arr’ stores the ‘r’ elements that have been traversed so far from the root-to-leaf.*/

void printpath(struct node *node)

{

if(node==NULL)

return ;

 

arr[r]=node->data;/*since ‘node’ is being traversed, it must added to the ‘arr’ array*/

r++;

 

if(node->left==NULL && node->right==NULL)

 

//PRINT ARRAY ‘arr’

return;

else

{

printpath(node->left,arr,r);

printpath(node->right,arr,r);

}

}

 
Go to top