Given a binary tree, print out all of its root-to-leaf paths.
/*
* Print array
*/
void printArray(int *path, int pathlen)
{
int i;
for(i = 0; i < pathlen; i++) {
printf("%d ",path[i]);
}
printf("\n");
}
/*
* Helper function to print all paths
*/
void printPathsRecur(nodeptr node, int path[], int pathLen)
{
path[pathLen] = node->data;
pathLen++;
if(node->left == NULL && node->right == NULL) {
printArray(path, pathLen);
} else {
printPathsRecur(node->left, path, pathLen);
printPathsRecur(node->right, path, pathLen);
}
}
/*
* Print all paths
*/
void printPaths(nodeptr node)
{
int path[200];
if(node != NULL)
{
printPathsRecur(node, path, 0);
}
}
/*
* Print array
*/
void printArray(int *path, int pathlen)
{
int i;
for(i = 0; i < pathlen; i++) {
printf("%d ",path[i]);
}
printf("\n");
}
/*
* Helper function to print all paths
*/
void printPathsRecur(nodeptr node, int path[], int pathLen)
{
path[pathLen] = node->data;
pathLen++;
if(node->left == NULL && node->right == NULL) {
printArray(path, pathLen);
} else {
printPathsRecur(node->left, path, pathLen);
printPathsRecur(node->right, path, pathLen);
}
}
/*
* Print all paths
*/
void printPaths(nodeptr node)
{
int path[200];
if(node != NULL)
{
printPathsRecur(node, path, 0);
}
}
No comments:
Post a Comment