Given a Binary Tree, find the maximum sum path from a leaf to root. For example, in the following tree, there are three leaf to root paths 8->-2->10, -4->-2->10 and 7->10. The sums of these three paths are 16, 4 and 17 respectively. The maximum of them is 17 and the path for maximum is 7->10.
10
/ \
-2 7
/ \
8 -4
This is a function to calculate maximum sum from root to any leaf node in the given binary tree. This problem is asked in interview many times by various companies. I am trying this declaring ls
and rs
as static, but it's producing wrong output. When I'm removing static
keyword it's producing correct output.
Can you please explain me what is the problem here with the static
keyword.
int roottoleafmaxsum(struct node*temp) //root will be passed as an argument
{
static int ls,rs; //left sum and right sum
if(temp) //if temp!=NULL then block will be executed
{
ls=roottoleafmaxsum(temp->left); //recursive call to left
rs=roottoleafmaxsum(temp->right); //recursive call to right
if(ls>rs)
return (ls+temp->data); //it will return sum of ls and data
else
return (rs+temp->data); //it will return sum of rs and data
}
}