B+树节点和

B+Tree Node sum

我正在尝试对某个深度的 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。

有什么想法吗?

给你的一些建议:

  1. 在递归调用中,您需要考虑如何获取结果并减少它们。在您的情况下,您忽略了递归调用的 return 值。

  2. 这个方法真的应该在BTreeNodeclass里面,这样你就可以避免访问实例变量keyc(应该是私有并且有更好的名字)。

  3. 习惯使用 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");
    }
}