繁体   English   中英

如何在java中的二叉树中找到或不存在节点?

[英]how to find an node exist or not in binary tree in java?

我试过这个,但我得到编译时错误。 我错过了什么? 如果找不到元素,我也必须返回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;
public boolean search(Node root, Node node){
    if(root == node){
        return true;
    }
    boolean found = false;

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

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

    return found;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM