【问题标题】:how to find an node exist or not in binary tree in java?如何在java中查找二叉树中是否存在节点?
【发布时间】:2015-02-10 09:32:52
【问题描述】:

我试过这个,但我得到编译时错误。我错过了什么?如果找不到元素,我也必须返回 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);
        }
    }

【问题讨论】:

  • 我的回答涵盖了编译错误,但您也有算法错误。我删除了答案。
  • 找不到节点怎么办?
  • 我编辑了答案以更正算法

标签: java algorithm binary-tree


【解决方案1】:
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;
}

【讨论】:

    【解决方案2】:

    你有一个编译错误,因为你并不总是返回一些东西:

        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;
    

    【讨论】:

    • 如果找不到元素怎么办?我必须返回 false
    猜你喜欢
    • 2019-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多