【问题标题】:Find function recursively Binary Tree递归查找函数二叉树
【发布时间】:2016-07-24 16:13:07
【问题描述】:

我在执行此功能时遇到了一点问题: 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

【问题讨论】:

    标签: java search recursion binary-tree


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2012-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-24
      • 2015-06-05
      • 2019-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多