2016-12-02 77 views
0

我有一個程序,我需要在二叉樹中搜索一個特定的詞,我爲該字符串的搜索方法提出的代碼不工作。如果有人可以看看它,我將不勝感激。二進制搜索樹字符串搜索

我已經嘗試了一些改動,但它仍然沒有工作。

public boolean check(BSTNode t,String key){ 
    if(!t.word.equals(key)){ 
     check(t.left,key); 
     check(t.right,key); 
    } 
    else{ 
     return true; 
    } 
    return false; 
} 
+0

我已編輯您的標籤。請確保選擇符合問題的標籤,而不僅僅是出現在您的問題中的單詞。例如,[tag:binary]標籤與二叉樹無關。這有助於在可以回答問題的人面前提出問題。我還添加了[tag:java]標記,因爲我相信你正在使用Java。現在堆棧溢出可以正確地突出顯示你的代碼。如果這是錯誤的語言,請更改它。 – Chris

回答

2

這可以寫成這樣;

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; 
} 
+0

非常感謝你花時間看我的代碼,我真的很感激。 – user7242310

+0

你打賭。如果您有任何問題,請告訴我。 – retrospectacus