栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

计算二叉树的最大路径和

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

计算二叉树的最大路径和

不多说代码奉上:

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

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;

}

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/983434.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号