在java中,如何在二叉树中查找节点是否存在?

在java中,如何在二叉树中查找节点是否存在?,java,algorithm,binary-tree,Java,Algorithm,Binary Tree,我尝试过这个,但是我得到了编译时错误。我错过了什么?如果找不到元素,我还必须返回false public boolean search(Node root, Node node){ if(root==node){ return true; } if(root.getLeft()!=null){ search(root.getLeft(), node); } if(ro

我尝试过这个,但是我得到了编译时错误。我错过了什么?如果找不到元素,我还必须返回false

public boolean search(Node root, Node node){
        if(root==node){
            return true;
        }
        if(root.getLeft()!=null){
            search(root.getLeft(), node);
        }

        if(root.getRight()!=null){
            search(root.getRight(), node);
        }
    }

您有一个编译错误,因为您并不总是返回某些内容:

    if(root.getLeft()!=null){
        search(root.getLeft(), node);
    }

    if(root.getRight()!=null){
        search(root.getRight(), node);
    }
这将修复编译错误,但不会修复算法:

    if(root.getLeft()!=null){
       return search(root.getLeft(), node);
    }

    if(root.getRight()!=null){
        return search(root.getRight(), node);
    }
    if(root.getLeft()!=null && search(root.getLeft(), node)) {
      return true;
    }

    if(root.getRight()!=null && search(root.getRight(), node)){
       return true;
    }
    return false;
这将修正算法:

    if(root.getLeft()!=null){
       return search(root.getLeft(), node);
    }

    if(root.getRight()!=null){
        return search(root.getRight(), node);
    }
    if(root.getLeft()!=null && search(root.getLeft(), node)) {
      return true;
    }

    if(root.getRight()!=null && search(root.getRight(), node)){
       return true;
    }
    return false;

如果找不到元素怎么办?我必须返回FALSE我的答案涵盖了编译错误,但你也有一个算法错误。我删除了答案。当找不到节点时会发生什么?我编辑了答案以更正算法