簡體   English   中英

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;

}

問題在於“和”將是每個元素的總和,但是最后它變為0。

有任何想法嗎?

為您提供一些建議:

  1. 在遞歸調用中,您需要考慮如何獲取結果並減少結果。 在您的情況下,您將忽略遞歸調用的返回值。

  2. 此方法實際上應該在BTreeNode類內,這樣您就可以避免訪問實例變量keyc (應為私有並具有更好的名稱)。

  3. 習慣於將Stream和collections用於這種類型的迭代操作,而不是傳統的迭代。

將所有內容放在一起:

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