gpt4 book ai didi

c++ - 我的逻辑正确吗?它给出了段错误

转载 作者:行者123 更新时间:2023-11-30 17:44:36 25 4
gpt4 key购买 nike

我想找到二叉树中从根到叶子的最大和。最初我正在做:Answer= sum_to_leaf(root,0);我知道另一种方法来探索所有路径并更新总和的全局最大值。我只是想这样做。

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;
}
}

最佳答案

嗯,您确定段错误来自该代码吗?你调试过吗?我宁愿尝试这个:

int sum_to_leaf(struct node* root,int sum) {

if(root==NULL) {
return sum;
} else {
sum=sum+root->data;
int left_sum = sum_to_leaf(root->left, sum);
int right_sum = sum_to_leaf(root->right, sum);

return std::max(left_sum, right_sum); // need to #include <algorithm>
}

}

关于c++ - 我的逻辑正确吗?它给出了段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19930514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com