Web Toolbar by Wibiya

Pages

Friday, January 6, 2012

Print all paths from root to leaf in a Binary tree.

Solution #1: To store the path, we need an array and an integer to store the length of the path. Here is the recursive algorithm,

void printAllPaths(struct node* root, int *arr, int len)
{
    if(root == NULL)
        return;

    arr[len++] = root->data;

    if((root->left == NULL) && (root->right==NULL))
    {
        int i=0;
        for(i=0; i < len; i++)
            printf("%d ", arr[i]);
        printf("\n");

        return;
    }

    printAllPaths(root->left, arr, len);
    printAllPaths(root->right, arr, len);
}

5 comments:

pnet said...

Nice Solution!

Chandra said...

Nice and simple solution.

Anonymous said...
This comment has been removed by the author.
Anonymous said...

Small correction.

10
/ \
11 12

The output will be:
10 11
10 11 12.

That's because after Left-sub-tree is called 10 and 11 will be added to array.
Array becomes |10|11|
10-->11

When Right-sub-tree of 10 is called, the array becomes
|10|11|12|
and hence 10-->11-->12 will be printed .
So reduce the 'len' variable as and when LST is called and finished.
Also reduce only if LST isnt NULL.

DO the same for RST as well .

http://ideone.com/LxXRVk

Anonymous said...

elegant