Web Toolbar by Wibiya

Pages

Saturday, January 7, 2012

Write a program to find a sub-tree in a Binary Search Tree whose sum is maximum.

Solution #1: Sum of a tree is the sum of all the nodes of that tree. We have to find a sub-tree whose sum is maximum. Clearly, this tree has negative elements as well otherwise the question is trivial and the original tree itself is the answer. Here is the recursive code,

int maxSum(struct node* root, int* max)
{
    if(root == NULL)
        return 0;

    int sum = maxSum(root->left, max) + maxSum(root->right, max) + root->data;

    if(sum > *max)
        *max = sum;

    return sum;
}

int main()
{
    struct node *root;

    insert(&root, -10);
    insert(&root, -20);
    insert(&root, 30);
    insert(&root, -5);
    insert(&root, 40);

    int max=0;

    maxSum(root, &max);
    printf("maxSum = %d\n", max);

    return 0;
}

3 comments:

Anonymous said...

if there is only one node with negative number, what result it will be?

Suchit Maindola said...

@Anonymous: In that case, max will remain 0. This behavior is similar to "Maximum contiguous subsequence sum" problem where if all the elements in the array are negative, we return 0.

Anonymous said...

the logic is right, except your initialization for max=0.
what if your bst is all negative?

change to:
max= MIN_INT;