使用Java在BST中搜索单词

时间:2015-07-28 05:02:59

标签: java binary-search-tree

我想检查这个词是否存在于BST中。

总是错误地给我false

if(listOfWords.contain(word))
write.print(word+" ");
// using this method but it does not work

private boolean contain(englishWord list, String word) {
    if (list != null) {
        contain(list.getLeft(), word);
        if (word.equals(list.getWord())) {
            return true;
        }
        contain(list.getRight(), word);
    }
    return false;
}

1 个答案:

答案 0 :(得分:1)

您的return true语句在递归中丢失了。

你可以使用类似的东西,

if (list != null) {
    if (word.equals(list.getWord()) || contain(list.getLeft(), word) || contain(list.getRight(), word)) {
        return true;
    }
}
return false;

但这需要O(n)时间复杂度。 BST旨在提供比这更好的表现。

如果您的BST按原样排列,那么这样的事情应该有效(并且比您的算法更有效)。

if (list != null) {
    int compare = word.compareTo(list.getWord());
    if (compare == 0) {
        return true;
    } else if (compare > 0) {
        return contain(list.getRight(), word);
    } else {
        return contain(list.getLeft(), word);
    }
}
return false;