0

我在编写将字符串单词插入二叉树的方法时遇到问题。下面的代码是有问题的方法。基本上,如果单词尚未在树中(作为 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;
}
4

1 回答 1

1

聊天结束后,您应该定义一个类,它同时具有 aStringint您用作放置在二叉树中的类型,以替换类型变量T。然后,您可以定义诸如getString()返回StringincrementFrequency()频率加一等方法。当您从二叉树中获取对象时,调用这些方法将是正确的类型。

于 2012-04-10T03:31:00.883 回答