计算二叉树的最大路径和

不多说代码奉上:

//计算单条路径的最大和

int maxInt(int arr[], int index, int size)

{

    int index1 = index * 2 + 1;

    int index2 = index * 2 + 2;

    if (index1 >= size || index2 >= size)

    {

        return arr[index];

    }

    int value1 = maxInt(arr, index1, size);

    int value2 = maxInt(arr, index2, size);

    if (value1 > value2)

    {

        return arr[index] + value1;

    }

    else

    {

        return arr[index] + value2;

    }

}

//

int MaxLengthTwoTree(int arr[],int size)

{

    int *a = new int[size];

    int maxValue = 0;

    int Value1 = 0;

    int Value2 = 0;

    int ind = 0;

    int MaxValue1 = maxInt(arr, 1, size); //第二层左侧的最大路径和

    int MaxValue2 = maxInt(arr, 2, size); //第二层右侧的最大路径和

    for (int i = 0; i < size; i++)

    {

        Value1 = 0;

        Value2 = 0;

        if (!i)

        {

            maxValue = maxInt(arr, i, size); //计算当前节点之下的最大路径和

        }

        else 

        {

            if (i*2 + 1 <= size && i * 2 + 2 <= size)

            {

                Value1 += maxInt(arr, i * 2 + 1, size);

                Value1 += maxInt(arr, i * 2 + 2, size);

                Value1 += arr[i];

            }

            else 

            {

                Value1 += arr[i];

            }

            int indexI = i;

            while (indexI >= 3)

            {

                if (indexI % 2 == 1)

                {

                    Value2 += arr[indexI];

                    indexI = (indexI - 1) / 2;

                }

                else 

                {

                    Value2 += arr[indexI];

                    indexI = (indexI - 2) / 2;

                }

            }

            if (indexI == 1)

            {

                Value2 += arr[indexI] + MaxValue2 + arr[0];

            }

            else if (indexI == 2)

            {

                Value2 += arr[indexI] + MaxValue1 + arr[0];

            }

            if (Value1 > Value2)

            {

                if (Value1 > maxValue)

                {

                    maxValue = Value1;

                }

            }

            else 

            {

                if (Value2 > maxValue)

                {

                    maxValue = Value2;

                }

            }

        }

    }

    return maxValue;

}

接受建议,如果上述代码不能够找到最大路径和的话,请让我知道二叉树数组。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值