I want to find the maximum sum from the root to a leaf in a binary tree.
Initially I am doing: Answer= sum_to_leaf(root,0);
I know the other way to explore all the path and update a global maximum for the sum. I just want to do it this way.
int sum_to_leaf(struct node* root, int sum)
{
if(root == NULL)
return sum;
else if(root->left == NULL && root->right == NULL)
{
sum = sum + root->data;
return sum;
}
else
{
sum = sum + root->data;
if(sum_to_leaf(root->left, sum) > sum_to_leaf(root->right, sum))
{
sum = sum + sum_to_leaf(root->left, sum);
}
else
{
sum = sum + sum_to_leaf(root->right, sum);
}
return sum;
}
}