c# - 查找二叉树中叶到根路径的最大总和

标签 c# algorithm multidimensional-array tree

我创建了一个递归函数来计算二叉树的最大路径。我得到的反馈是它不起作用,但根据我的测试,它提供了正确的结果。有人能帮助我吗?

private long PathSum(int row, int column, Pyramid pyramid)
{
    // Base case, stop recurse when first row is reached.
    if (row == 0) return pyramid[row, column];

    // Set level to the current cell and add to the end result.
    long value = pyramid[row, column];

    // Continue to the next row.
    if (row != 0)
    {
        // Continue to the next left level.
        long left = pyramid[row - 1, column];

        // Continue to the next right level.
        long right = pyramid[row - 1, column + 1];

        // Get the highest of the left and right.
        long highest = Math.Max(left, right);

        // Get the index of the hightest path.
        int nextColumn = highest == left ? column : column + 1;

        // Recurse to the next level and add results together.
        value += GetTotal(row – 1, nextColumn, pyramid);
    }
    // Return result to the caller.
    return value;
}

最佳答案

您的算法存在一个严重错误:您只遍历“金字塔”一次,然后根据下一个结果选择基本案例,而没有查看底层节点。 为了说明您正在做什么,请考虑以下金字塔:

     1
   2   3
311  6    3

假设从1开始,将执行以下内容:

  1. 查看底层节点的最大值(2 和 3)。
  2. 向下移动到下一个节点 (3) 并重复。

您的算法将返回 10 (1 + 3 + 6),而我的示例中的最大值是 311 + 2 + 1,因为它不会向前看。

您需要一种策略来向前迈进一步,以确定最佳路径。

编辑:查看Euler project #18 approach获取更多提示。

关于c# - 查找二叉树中叶到根路径的最大总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21165029/

相关文章:

c# - Webjob 未使用正确的配置发布

c# - 如何捕获进程的标准输出/错误?

algorithm - 查找总长度总和最大的非重叠范围

algorithm - 2^(2^n) 或 n^(2n) 哪个增长更快

c++ - 在C++中定义二维数组的最简单方法

java - 寻找二维数组中的特定元素

c# - 轮询 SSIS 执行状态

c# - Visual Studio : find all references of a specific type

c - 双链表、MergeSort,得到未定义和不可靠的结果

c++ - 文本文件中的值未写入二维数组?