2012-04-10 63 views
0

我遇到了一个方法,我写入字符串字插入二进制树的方法。下面的代码是有问题的方法。基本上,如果该单词尚不在树中(如BinaryTreeNode),则插入该单词,如果该单词在树中,则其频率(在BinaryTreeNode内的计数变量)将增加1。我的问题是与临时变量searchWord。将其定义为String会产生类型不匹配,并且getFrequency()未被定义为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; 
} 

频率get/set方法:

/** 
* 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; 
} 
+0

getFrequency方法在哪里定义? – 2012-04-10 03:30:19

+0

'BinaryTreeNode()'。 – lollercopter 2012-04-10 03:32:33

回答

1

聊天交谈后,你应该定义一种既具有类一个Stringint您使用作为类型以plac e在二叉树中替换类型变量T。然后,您可以定义诸如getString()之类的方法来返回String,incrementFrequency()以将频率添加到等。当您从二叉树中获取对象时,它将是调用这些方法的正确类型。

+0

这样做后,我收到消息'类型不匹配:无法从对象转换为BinaryTreeNode'。我应该提到'find()'返回一个'T'类型的对象。 – lollercopter 2012-04-10 03:32:19

+0

发布你的词树代码。 – 2012-04-10 03:32:50

+0

'wordTree'是一棵二叉树。我不确定“发布代码”是什么意思,因为它只是单行定义。你需要二叉树类中的任何特定方法吗? – lollercopter 2012-04-10 03:36:14