I’m having trouble with a method I wrote to insert string words into a binary tree. The below code is the method in question. Basically, the word is inserted if it is not yet in the tree (as a BinaryTreeNode), and if it is in the tree, its frequency (count variable within BinaryTreeNode) is increased by one. My problem is with the temporary variable searchWord. Defining it as a String creates a type mismatch and a statement that says getFrequency() is not defined for type String. The generic type T is only there as a placeholder – it too does not work. What should it therefore be defined as?
buildBinaryTree method:
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 constructor:
/**
* 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;
}
Frequency get/set methods:
/**
* 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;
}
After talking in chat, you should define a class that has both a
Stringandintthat you use as the type to place in the binary tree, to replace the type variableT. Then, you can define methods such asgetString()to return theString,incrementFrequency()to add one to the frequency, etc. When you get an object out of the binary tree, it will be the right type to call these methods.