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

Comments (0)
Trackbacks (0)
Leave a comment
Trackback