我正在嘗試遍歷二叉樹并在每個節點前面列印出具有匹配數字的節點值。為了更好地理解:我在呼叫我的方法時列印出以下幾行:
- 11 , 2. 33 , 3. 10 , 4. 14 , 5. 27 , 3. 31 , 4. 32
作為我的方法的目標,列印出完全相同的節點順序,但前面的數字會增加,這應該表明順序。像這樣:
- 11
- 33
- 10
- 14
- 27
- 31
- 32
直到知道我的方法看起來像這樣:
public int mNr(Node k, int Nr) {
//If the current Node is null, return 0 (currently not making any use of the return)
if(k == null) {
return 0;
} else {
//If the left Side is not null print out the Left Node with Value
if(k.left != null) {
//increment Nr each time priniting
System.out.println("Nr: " Nr " " k.left.number);
}
if(k.right != null) {
//Same as left Side
System.out.println("Nr: " Nr " " k.right.number);
}
//Calling the Method and not incrementing the Nr Parameter because
//already incrementing it in the print Statements
return mNr(k.left, Nr) mNr(k.right, Nr);
}
}
我也不太確定如何使用int -return,即使知道我沒有使用它。任何獲得正確輸出的建議都會有所幫助。
uj5u.com熱心網友回復:
由于每個遞回呼叫都有自己的Nr變數,它們并不總是具有相同的值。如果在更深層次的遞回Nr中增加,這不會影響呼叫者的Nr.
正如您似乎已經暗示的那樣,您可以使用回傳值將最新值傳達給呼叫者Nr,以便呼叫者可以更新自己的Nr變數,或者根據呼叫者的意愿使用它。
這是一個更正:
public int mNr(Node k, int Nr) {
if(k == null) {
return 0;
} else {
if(k.left != null) {
System.out.println("Nr: " Nr " " k.left.number);
}
if(k.right != null) {
System.out.println("Nr: " Nr " " k.right.number);
}
// Use the return value from the left-recursion to feed the right-recursion
return mNr(k.right, mNr(k.left, Nr));
}
}
話雖如此,這種遍歷還有一些其他問題:
- 根節點不包含在輸出中
- 遍歷有一個特殊的順序:它首先是深度和廣度的混合。選擇更流行的遍歷會更有意義,例如前序遍歷(第一個父節點,然后是左子樹,然后是右子樹)
因此,這導致以下替代代碼:
static public int mNr(Node node, int Nr) {
if (node == null) {
return Nr;
}
System.out.println("Nr: " Nr " " node.number);
return mNr(node.right, mNr(node.left, Nr));
}
uj5u.com熱心網友回復:
回傳用于使方法的結果可用于程式中的進一步評估。在這種情況下,方法呼叫mNr可以使用回傳的 0 來知道節點是空的,因此針對這種情況產生更充分的輸出。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/417797.html
標籤:
上一篇:自下而上搜索以過濾嵌套選單陣列
下一篇:轉換為尾遞回
