【发布时间】:2011-04-12 15:40:57
【问题描述】:
我目前正在尝试创建一种方法,该方法使用二叉树来查找用户输入的单词的字谜。
如果树不包含单词的任何其他字谜(即,如果键不在树中或关联链表中的唯一元素是用户提供的单词),则消息“找不到字谜” "被打印出来 例如,如果键“opst”出现在树中,其关联的链表包含单词“spot”、“pots”和“tops”,并且用户给出了单词“spot”,程序应该打印“pots”和“tops”(但不是现货)。
public boolean find(K thisKey, T thisElement){
return find(root, thisKey, thisElement);
}
public boolean find(Node current, K thisKey, T thisElement){
if (current == null)
return false;
else{
int comp = current.key.compareTo(thisKey);
if (comp>0)
return find(current.left, thisKey, thisElement);
else if(comp<0)
return find(current.right, thisKey, thisElement);
else{
return current.item.find(thisElement);
}
}
}
虽然我创建了这个方法来查找提供的元素是否在树中(以及关联的键),但我被告知不要重复使用此代码来查找字谜。
K 是泛型类型,扩展 Comparable 并表示 Key,T 是泛型类型,表示列表中的一项。
如果需要我已经完成的额外方法,我可以编辑这篇文章,但我完全迷失了。 (只需要指向正确方向的指针)
【问题讨论】:
-
你写的方法,最好叫
contains('是这棵树的关键吗?')。要使其成为find方法,它应该返回找到的内容。
标签: java binary-tree