2016-04-04 148 views
0

我有一點問題,這樣的功能: public boolean find(Integer i)查找功能遞歸二叉樹

起初我想:

public boolean find(Integer i) { 
    Node currNode = root; 

    if (currNode.getData() != i) { 
     return false; // we didnt find it 
    } 
    if (currNode.getLeft() != null && find(currNode.getLeft().getData())) { 
     return true; 
    } 
    if (currNode.getRight() != null && find(currNode.getRight().getData())) { 
     return true; 
    } 
    else 
     return false; 
} 

但這只是給了我false在我的測試案例。如果在二叉樹內找到輸入數據,我想知道如何在二叉樹中找到特定數據並返回true

回答

0

根據您所提供的代碼,我猜這更像是你想要什麼:

public boolean find(Integer i) { 

    if (getData().intValue() == i.intValue()) { 
     return true; // we found it 
    } 

    if (getLeft() != null && getLeft().find(i)) { 
     return true; 
    } 

    if (getRight() != null && getRight().find(i)) { 
     return true; 
    } 

    return false; 
} 

如果不是,提供更多的解決方案的代碼,以幫助指導一個更好的答案。