我试图在一定深度上对B+树节点的所有元素进行汇总。
以下是代码:
public static int printSumAtD(BTreeNode T, int d) {
if(d == 0) {
int sum;
for (int i = 0; i < T.key.length; i++) {
sum = sum + T.key[i];
}
return sum;
} else {
if(T.isLeaf)
return 0;
else{
for(int i = 0; i < T.n+1; i++) {
printSumAtD(T.c[i], d-1);
}
}
}
return 0;
}问题是," sum“将是每个元素的和,但是在最后它会变为0。
有什么想法吗?
发布于 2017-11-01 05:49:29
以下是给你的一些建议:
BTreeNode类中,这样就可以避免访问实例变量key和c (它们应该是私有的,并且有更好的名称)。Stream和集合,而不是传统的迭代。把所有这些放在一起:
class BTreeNode {
private int value;
private List<BTreeNode> children;
public int sumAtDepth(int depth) {
if (depth == 0)
return value;
else if (depth > 0)
return children.stream()
.mapToInt(c -> c.sumAtDepth(depth - 1)).sum();
else
throw new IllegalArgumentException("Negative depth");
}
}https://stackoverflow.com/questions/47048519
复制相似问题