给定二叉树,找到从叶到根的最大总和路径。例如,在以下树中,有三个叶子到根路径8 - > - 2-> 10,-4 - > - 2-> 10和7-> 10。这三条路径的总和分别是16,4和17。它们的最大值是17,最大值的路径是7 - > 10。在二叉树中查找从根到叶的最大总和
10
/\
-2 7
/\
8 -4
这是计算从根本最高数额在给定二叉树的任何叶子节点的功能,这个问题是问在采访中也多次通过各种companies.I我想这个声明LS和RS作为静..所以它会产生错误的输出。但是当我删除静态关键字时,它会产生正确的输出。请给我解释一下静态关键字的问题。
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
}
}
我想你应该在你的roottoleafmaxsum函数中当temp为NULL时返回0。 – IronMan007