【发布时间】:2015-09-29 06:31:25
【问题描述】:
我必须找到从根节点到叶节点的最大总和。 我想出了以下节点,但它没有给出正确的输出。树可以有两个以上的子节点(它不是二叉树)。
public static long findBestPath(Path path) {
long max = 0, sum = 0;
if (path.getChildren().size() == 0)
return path.getValue();
else if (path.getChildren().size() == 1)
return path.getValue() + findBestPath(path.getChildren().get(0));
else {
for (int i = 0; i < path.getChildren().size(); i++) {
sum = path.getChildren().get(i).getValue() + findBestPath(path.getChildren().get(i));
if (sum > max)
max = sum;
}
return max;
}
}
我使用了另一种方法来解决我的问题。虽然最好知道正确的解决方案来找到非二叉树的最大和路径。
【问题讨论】: