Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.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 二叉搜索树的搜索前缀方法_Java_Binary Search Tree_Tail Recursion - Fatal编程技术网

Java 二叉搜索树的搜索前缀方法

Java 二叉搜索树的搜索前缀方法,java,binary-search-tree,tail-recursion,Java,Binary Search Tree,Tail Recursion,我正在尝试为我的字典程序实现一个搜索前缀方法。它在二叉搜索树中搜索前缀,例如“t”或“th”表示“the”。到目前为止,它总是返回false。令人困惑的是,我有一个非常相似的方法来查找整个单词,而且效果很好。这个方法也使用了与通常的BST方法非常相似的技术。如有任何建议,将不胜感激 private boolean recContainsPrefix(String prefixKey, BSTNode<String> tree){ //base case if(tree

我正在尝试为我的字典程序实现一个搜索前缀方法。它在二叉搜索树中搜索前缀,例如“t”或“th”表示“the”。到目前为止,它总是返回false。令人困惑的是,我有一个非常相似的方法来查找整个单词,而且效果很好。这个方法也使用了与通常的BST方法非常相似的技术。如有任何建议,将不胜感激

private boolean recContainsPrefix(String prefixKey, BSTNode<String> tree){
    //base case
    if(tree==null)

    return false;
    //test if each node starts with the prefix.
    if(tree.getInfo().startsWith(prefixKey)){
        return true;
    }
    //recursive case.
    else if(prefixKey.compareTo(tree.getInfo())<0)
        return recContainsPrefix(prefixKey, tree.getLeft());
    //recursive case.
    else if(prefixKey.compareTo(tree.getInfo())>0)
        return recContainsPrefix(prefixKey, tree.getRight());

    else{
        return true;
    }
}       
private boolean recContainsPrefix(字符串前缀键,BSTNode树){
//基本情况
if(tree==null)
返回false;
//测试每个节点是否以前缀开头。
if(tree.getInfo().startsWith(prefixKey)){
返回true;
}
//递归案例。
else if(prefixKey.compareTo(tree.getInfo())0)
返回recContainsPrefix(prefixKey,tree.getRight());
否则{
返回true;
}
}       

由于它使用递归,因此在
的自底向上递归中永远不会满足尾部条件

if(tree.getInfo().startsWith(prefixKey))
 { 
   return true; 
   }
如果是,则将条件反转为:

if(prefixKey.startsWith(tree.getInfo()))
     { 
       return true; 
       }

请尝试
if(tree==null){return false;}
,因为我认为if语句下的空行会影响代码流。非常感谢您的建议!但是,这似乎不起作用。如果这听起来很愚蠢,很抱歉,但是您可以显示getInfo()为树中的节点返回了什么吗。因为我怀疑比较
if(tree.getInfo().startsWith(prefixKey)){return true;}
,如果自上而下,字符串将永远不会满足。就像“t”永远不会以“th”开头…“th”永远不会以“the”开头…谢谢!你知道解决这个问题的方法吗?