我有一个二叉搜索树,其中的单词存储在节点中作为数据。我正在尝试编写一个findWord方法,如果给定的单词在BST中,它将返回true / false。如果BST中至少存在一个具有给定前缀的单词,则我的findPrefix方法应该返回true / false。
现在我有了这个
public boolean findWord ( String word) {
return contains(word, root);
}
public boolean findPrefix (String prefix ) {
return contains(prefix, root);
}
我的包含方法就是这个
protected boolean contains(E item, BSTNode<E> tree) {
if(tree==null)
return false;
else if(item.compareTo(tree.getInfo())<0)
return contains(item, tree.getLeft());
else if(item.compareTo(tree.getInfo())>=0)
return contains(item, tree.getRight());
else
return true;
}
我很确定我应该为findWord和findPrefix方法提供更多代码,除非我的contains方法是错误的。谢谢!
答案 0 :(得分:0)
考虑到您的树和其他实现是正确的,以下更改将帮助您找到与BST中的任何节点匹配(如果)的前缀或单词:
// root passed from method call for a node
public boolean findWord (String word,String root) {
return root.equals(word);
}
public boolean findPrefix (String prefix,String root) {
return root.contains(prefix);
}
protected boolean contains(E item, BSTNode<E> tree) {
String lookingFor = "searchTHISword";
if(tree==null)
return false;
if(findWord(lookingFor,tree.getInfo())) {
System.out.println("Found the entire word here.");
return true;
}
if(findPrefix(lookingFor,tree.getInfo())){
System.out.println("Found the word as a prefix here.");
return true;
}
if(item.compareTo(tree.getInfo())<0)
return contains(item, tree.getLeft());
else
return contains(item, tree.getRight());
}
// Would return false, it what you are looking for is nowhere in the BST