不多说代码奉上:
//计算单条路径的最大和
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;
}
接受建议,如果上述代码不能够找到最大路径和的话,请让我知道二叉树数组。