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

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


http://puddleofriddles.blogspot.com/2012/01/write-program-to-find-sub-tree-in.html

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=MIN_INT;

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

    return 0;
}
Advertisements
Categories: programming
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: