我正在從頭開始在java中構建一個樹結構。為了獲得我的樹的高度,我使用了遞回函式。
每個注釋 (IP) 都包含它擁有的所有連接的串列,包括那里的父級。我的想法是遍歷所有子節點,并在它不是父節點時再次呼叫 height 函式。
我的問題是,它只呼叫一個孩子并且不會遍歷所有可能的孩子。也許有人可以告訴我我的錯在哪里。
如果一個 Note 有兩個孩子,并且每個孩子還有另外兩個。它只在兩次迭代中查看第一個。
public int recursiveGetHight(final Node node, Node parent) {
Node viewPoint = getViewPoint(node);
int h = 0;
for (Node child : viewPoint.getChildren()) {
if (child.getChildren().size() <= 1) {
return 0;
} else if(parent == null || child.getValue() != parent.getValue()){
h = recursiveGetHight(child, viewPoint) 1;
return h;
}
}
return h;
}
例:
root
- note 1
- sub note 1
- sub note 2
- x
- y
- note 2
- sub note 1
- z
- sub note 2
int h = recurisvHeight(root, null)
result should be 3 but the function returns 2.
如果我在 for 回圈內的列印命令
System.out.println(child);
它顯示:note1 sub note 1
uj5u.com熱心網友回復:
這是因為您使用 return,當您回傳時,您的函式結束。您必須洗掉第一個 return = 0 并創建一個子陣列串列,并通過將子元素附加到串列中來替換 by 回圈中的 return h。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/434910.html
上一篇:Python遞回函式搜索二叉樹
下一篇:數的數積
