Web Toolbar by Wibiya

Pages

Friday, January 6, 2012

Write a function to check whether there exists a root to leaf path sum equal to a given number.

Solution #1: Here is the recursive code,

int hasSum(struct node* root, int sum)
{
    if(root == NULL)
        return (sum == 0);

    sum = sum - root->data;

    return hasSum(root->left, sum) || hasSum(root->right, sum);
}

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);
}