【问题标题】:Find maximum sum leaf to root path in a Binary Tree [closed]在二叉树中找到最大和叶到根路径[关闭]
【发布时间】:2014-02-05 13:14:16
【问题描述】:

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

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

【问题讨论】:

  • 询问反馈,他们期望什么,他们得到什么,然后尝试调试。这对于 c Math.Max(left, right) 来说也很可疑。
  • 这看起来不像 C 代码 - 更像 Java 或 C#。这是什么语言? Pyramid 是什么?
  • 我问了,但他们不能告诉我更多。正如我所说,我对其进行了测试,对我来说效果很好。
  • 不好意思,是C#,我也在用C开发。:-(
  • 你的测试好像没有完成,多做测试用例多多反馈。也许你错过了 pyramid[row - 1, column - 1];

标签: c# algorithm multidimensional-array tree


【解决方案1】:

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

     1
   2   3
311  6    3

假设你从1开始,会执行如下:

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

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

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

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

【讨论】:

  • 谢谢Bas,我刚刚解决了Euler Project的2nd。所以,我必须去看看 18 号。
  • 嗨,Bas,你能告诉我哪个是错误的部分吗? isidorouk@yahoo.co.uk
【解决方案2】:

我认为您所描述的不是二叉树,而是数字金字塔,最好使用动态编程而不是树遍历来解决问题。这是动态编程的示例代码。它没有编译,顺便说一下我不懂C#:

private long DP(int maxRow, Pyramid pyramid) 
{
    int maxColumn = maxRow;
    Pyramid result; 
    clear_pyramid(result); 
    for (int j=0; i<maxColumn; i++) {
        result[0, j] = pyramid[0, j];
    }    
    for (int i=1; i<maxRow; i++) {
        for (int j=0; j<maxColumn-i; j++) {
            result[i,j] = Math.max(result[i-1,j], result[i-1,j+1]) + pyramid[i,j];
        }    
    }
    return result[maxRow-1, 0];
}

【讨论】:

  • 金字塔实际上是一种二叉树。
  • 哦,为什么,我猜你提到的金字塔在第 n 层有 2^n 个数字?如果我们在谈论 n 层有 n+1 个数字的金字塔,那么我认为它不是一棵树。比如我们有 1 在级别 0,2 3 在级别 1,4 5 6 在级别 2,那么 2 和 3 都连接到 1 和 5,这意味着它们之间有两条路径,这与定义相矛盾树。
  • @justinzhang 树只是一个没有循环的图。一个节点是两个不同节点的子节点这一事实并不意味着它不是一棵树。如果它不是一棵树,则节点必须将其祖先之一(或自身)作为其子节点,从而创建一个循环。
猜你喜欢
  • 1970-01-01
  • 2016-08-03
  • 2022-11-04
  • 1970-01-01
  • 2016-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多