這可以寫成這樣;
public boolean check(BSTNode t,String key) {
return
t.word.equals(key) || check(t.left,key) || check(t.right,key)
}
或更詳細地說;
public boolean check(BSTNode t,String key) {
if (t.word.equals(key)) return true;
if (check(t.left,key)) return true;
if (check(t.right,key)) return true;
return false;
}
因爲return
報表功能停止執行,你不需要很多的else
聲明。
編輯:
您還必須檢查你的BSTNode不爲空,或者當你到達樹的最後,你會得到空指針異常。這可能在函數的開始做,或之前內部遞歸調用check
:
public boolean check(BSTNode t,String key) {
if (t == null) return false;
if (t.word.equals(key)) return true;
if (check(t.left,key)) return true;
if (check(t.right,key)) return true;
return false;
}
;或
public boolean check(BSTNode t,String key) {
if (t.word.equals(key)) return true;
if (t.left != null && check(t.left,key)) return true;
if (t.right != null && check(t.right,key)) return true;
return false;
}
我已編輯您的標籤。請確保選擇符合問題的標籤,而不僅僅是出現在您的問題中的單詞。例如,[tag:binary]標籤與二叉樹無關。這有助於在可以回答問題的人面前提出問題。我還添加了[tag:java]標記,因爲我相信你正在使用Java。現在堆棧溢出可以正確地突出顯示你的代碼。如果這是錯誤的語言,請更改它。 – Chris