print all the root-to-leaf paths per line of a Binary Tree

PROBLEM :

Given a binary tree, print out all of its root-to-leaf paths one per line.

Example:
Example Tree


Output for the above example will be

  1 2 4
  1 2 5
  1 3

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/*
typedef struct BST
{
int info ;
struct BST *left ;
struct BST *right ;
}tree ;------------------------------*/

void print_path(tree *,int [],int ) ;
void print(int [],int ) ;

void print_tree_path(tree *root)
{
int path[1000] ;
print_path(root,path,0) ;
}

void print_path(tree *root,int path[],int pathlen)
{
if(root==NULL)
return ;

path[pathlen]=root->info ;
pathlen++ ;

if(root->left==NULL&&root->left==NULL)
print(path,pathlen) ;
else
{
print_path(root->left,path,pathlen) ;
print_path(root->right,path,pathlen) ;
}
}

void print(int path[],int pathlen)
{
int i ;
for(i=0;i<pathlen;i++)
cout<<path[i]<<" " ;
cout<<endl ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )