我在编写将字符串单词插入二叉树的方法时遇到问题。下面的代码是有问题的方法。基本上,如果单词尚未在树中(作为 a BinaryTreeNode
),则插入该单词,如果它在树中,则其频率(在 内的计数变量BinaryTreeNode
)增加一。我的问题是临时变量searchWord
。将其定义为 aString
会创建类型不匹配和声明getFrequency()
未为 type 定义的语句String
。泛型类型T
仅作为占位符存在 - 它也不起作用。因此它应该被定义为什么?
buildBinaryTree 方法:
public static void buildBinaryTree(String word) {
//if word is already in tree
if(wordTree.contains(word)) {
//find existing word node
T searchWord = wordTree.find(word); //problem here
//increment frequency by 1
searchWord.setFrequency(searchWord.getFrequency() + 1);
} else {
//add word to tree
System.out.println(word);
wordTree.addElement(word);
}
}
BinaryTreeNode 构造函数:
/**
* Creates a new tree node with the specified data.
* @param obj the element that will become a part of the new tree node
*/
BinaryTreeNode(T obj) {
element = obj;
left = null;
right = null;
frequency = 1;
}
频率获取/设置方法:
/**
* Gets the frequency.
* @return the frequency
*/
public int getFrequency() {
return frequency;
}
/**
* Sets the frequency.
* @param frequency the frequency to set
*/
public void setFrequency(int frequency) {
this.frequency = frequency;
}