0

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

3 回答 3

0

我想实现你的算法的更好方法是:

int getSum(struct node* nd)
{
    if(nd==NULL)
        return 0;
    int sum_r = getSum(nd->right);
    int sum_l = getSum(nd->left);
    return nd->data + std::max(sum_r, sum_l);
}
于 2013-11-12T16:32:19.440 回答
0

您一定是错误地构建了您的树。在某个地方,您正在访问未初始化的node文件root->并遇到段错误。

于 2013-11-12T13:37:30.673 回答
0

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

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

}
于 2013-11-12T13:38:17.947 回答