【发布时间】: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