以Pre Order Traversal方式搜索

时间:2014-12-02 06:47:37

标签: java search binary-tree tree-traversal preorder

我有一个二叉搜索树。我知道如何使用搜索属性进行搜索。但我的任务是在不使用搜索属性的情况下搜索树。(比方说,在二叉树中搜索)这就是我必须搜索的方式。

1 即可。如果您发现当前节点中的值返回它。

2 即可。否则搜索右边。如果未在右侧找到,则在左侧搜索

第3 即可。如果在整个树中找不到,则返回null。

这就是我的尝试。

public Node search(int val)
{
    Node target = this;
    if(target.getVal() == val)
        return this;
    else if(target.getRight() == null && target.getLeft() == null)
        return null;
    if(target.getRight() != null)
    {
        return target.getRight().search(id);
    }
    if(target.getLeft() != null)
    {
        return target.getLeft().search(id);
    }
    return null;
}

我的代码问题是,如果正确的孩子存在并且没有找到val,我获得null值。 (不在左边搜索)。如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

这是未经测试的代码,但我会改变你的逻辑:

public Node search(int val)
{
    if(this.getVal() == val)
        return this;

    if (this.getRight() != null) {
        Node right = this.getRight().search(id);
        if (right != null)
            return right;
    }

    if (this.getLeft() != null) {
        Node left = this.getLeft().search(id);
        if (left != null)
            return left;
    }

    return null;
}

在您的版本中,您将返回一个解决方案,其唯一要求是右侧或左侧的节点不为空。只有在找到解决方案时才需要返回解决方案。

答案 1 :(得分:0)

public Node search(int val)
{
    Node target = this;
    if(target.getVal() == val)
        return this;
    else if(target.getRight() == null && target.getLeft() == null)
        return null;
    if(target.getRight() != null)
    {
        return target.getRight().search(id); //here lies the problem
    }
    if(target.getLeft() != null)
    {
        return target.getLeft().search(id);
   }
return null;

}

代码中的问题是您在正在搜索的节点的右子树中返回搜索结果。

这是更新后的代码

public Node search(int val)
{
    Node target = null;
    if(this.getVal() == val)
    {
        return this;
    }
    else if(this.getRight() == null && this.getLeft() == null)
        return target;
    if(this.getRight() != null)
    {
        target = this.getRight().search(id);
    }
    if(target==null && this.getLeft() != null)
    {
        target = this.getLeft().search(id);
   }
   return target;

}