简体   繁体   English

B +树节点总和

[英]B+Tree Node sum

I am trying to sum all the elements of a B+ Tree Node at a certain Depth. 我试图以某个深度求和B +树节点的所有元素。

Here is the code: 这是代码:

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;

}

The problem is that "sum" would be the sum of each element, however at the end it goes to 0. 问题在于“和”将是每个元素的总和,但是最后它变为0。

Any ideas? 有任何想法吗?

A number of suggestions for you: 为您提供一些建议:

  1. in recursive calls you need to consider how you will take the results and reduce them. 在递归调用中,您需要考虑如何获取结果并减少结果。 In your case you are ignoring the return value of the recursive calls. 在您的情况下,您将忽略递归调用的返回值。

  2. This method should really be inside the BTreeNode class so that you can avoid access instance variables key and c (which should be private and have better names). 此方法实际上应该在BTreeNode类内,这样您就可以避免访问实例变量keyc (应为私有并具有更好的名称)。

  3. Get used to using Stream and collections for this type of iterative operation rather than traditional iteration. 习惯于将Stream和collections用于这种类型的迭代操作,而不是传统的迭代。

Putting all that together: 将所有内容放在一起:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM