Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/security/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java-BST递归查找值_Java_Recursion_Binary Search Tree - Fatal编程技术网

java-BST递归查找值

java-BST递归查找值,java,recursion,binary-search-tree,Java,Recursion,Binary Search Tree,我有一棵BST树。我想创建一个方法,获取一个值并返回包含其值的节点级别(root=0),没有这样的节点吗?返回-1。 我想反复做这件事。 这段代码工作得很好: private int recursiveContains(BinaryNode node, int searchVal){ int nodeKey = node.nodeKey; if (searchVal < nodeKey){ if (node.leftChild != EMPTY_NO

我有一棵BST树。我想创建一个方法,获取一个值并返回包含其值的节点级别(root=0),没有这样的节点吗?返回-1。 我想反复做这件事。 这段代码工作得很好:

    private int recursiveContains(BinaryNode node, int searchVal){
    int nodeKey = node.nodeKey;
    if (searchVal < nodeKey){
        if (node.leftChild != EMPTY_NODE)
            return 1 + recursiveContains(node.leftChild, searchVal);
    }else if (searchVal > nodeKey){
        if (node.rightChild != EMPTY_NODE)
            return 1 + recursiveContains(node.rightChild, searchVal);
    }
    return 0;
}
private int recursiveContains(二进制节点,int searchVal){
int nodeKey=node.nodeKey;
if(searchValnodeKey){
if(node.rightChild!=空节点)
返回1+recursiveContains(node.rightChild,searchVal);
}
返回0;
}
但是,仅当树包含搜索值时

当我到达一个叶并且没有找到值时,如何停止迭代并返回-1? 有可能是递归的吗


谢谢

您只需要调整您的最终案例。现在,如果该值不在树中,则只返回将插入该值的节点的深度,因为最后一个大小写是
返回0
。相反,您需要显式检查当前节点是否确实是正确的节点。如果是,您可以返回
0
;否则,应返回
-1
。然后,递归调用需要查找该特殊值并适当地处理它

我可能会把这个显式检查放在开头,基本情况是请求的节点。最后,您的“fall-through”值(如果其他条件均不成立,则返回的值)为
-1
。所以你会得到这样的结果:

// WARNING: UNTESTED CODE
if (searchVal == nodeKey) {
    return 0;
} else if (searchVal < nodeKey && node.leftChild != EMPTY_NODE) {
    int childResult = recursiveContains(node.leftChild, searchVal);
    if (childResult != -1) { // Only use the child result if the value was found.
        return 1 + childResult;
    }
} else if (searchVal > nodeKey && node.rightChild != EMPTY_NODE) {
    int childResult = recursiveContains(node.rightChild, searchVal);
    if (childResult != -1) { // Only use the child result if the value was found.
        return 1 + childResult;
    }
}
// If you haven't returned by now, the value can't be found along this path.
return -1;
//警告:未测试的代码
if(searchVal==nodeKey){
返回0;
}else if(searchValnodeKey&&node.rightChild!=空节点){
int childResult=recursiveContains(node.rightChild,searchVal);
if(childResult!=-1){//仅在找到值时使用子结果。
返回1+childResult;
}
}
//如果您现在还没有返回,则无法在此路径上找到该值。
返回-1;

仍不工作。如果未找到节点,则返回最近节点的高度-1@user3150902正如我在第一段末尾提到的,您仍然需要考虑递归调用中可能的-1值,并适当地处理它们。我在一些示例代码中进行了编辑,以说明我的意思:如果递归调用返回-1,则不应该返回它:只需让它变成“notfound”值即可。