递归查找函数二进制树



我在执行此函数时遇到了一些问题: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

根据您提供的代码,我猜这更像您想要的:

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

如果没有,请提供更多的解决方案代码,以帮助指导更好的答案。

最新更新