Saturday, December 6, 2008

One more Print path

A well known problem to the job seekers:

Given a binary tree, print out all of its root-to-leaf paths as defined above. This problem is a little harder than it looks, since the "path so far" needs to be communicated between the recursive calls. Hint: In C, C++, and Java, probably the best solution is to create a recursive helper function printPathsRecur(node, int path[], int pathLen), where the path array communicates the sequence of nodes that led up to the current call. Alternately, the problem may be solved bottom-up, with each node returning its list of paths. This strategy works quite nicely in Lisp, since it can exploit the built in list and mapping primitives. (Thanks to Matthias Felleisen for suggesting this problem.)

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

void printPaths(struct node* node) 

Solution you can find easily at : http://cslibrary.stanford.edu/110/BinaryTrees.html

I have not find any new solution till date for this:

I have tried derive new one today (not implemented yet.. )

#include

using namespace std;

printPath(node* root){

string now="";

ppath(root, now); 

}

ppath(node* root, string now){

if(!root) return;

if( root && ! root->left && ! root->right){

print("%s %d\n", now, root->data); return;

}

if(root->left) ppath(root->left, now+'0'+root->data);

if(root->right) ppath(root->right, now+'0'+root->data);

}


Although solution is very simple still like to point out the concept of using string.


string class have following properties:

string+char->string.

and passing string as value to a function will create a new string. 

Please comment the correctness of solution.