[英]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。
有任何想法嗎?
為您提供一些建議:
在遞歸調用中,您需要考慮如何獲取結果並減少結果。 在您的情況下,您將忽略遞歸調用的返回值。
此方法實際上應該在BTreeNode
類內,這樣您就可以避免訪問實例變量key
和c
(應為私有並具有更好的名稱)。
習慣於將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.