【发布时间】:2015-05-02 13:21:05
【问题描述】:
此函数的目的是获取用户输入以查找已添加到二叉搜索树的单词。然后使用我在BST中的搜索算法,如果找到了这个词,就打印出这个词的出现频率。我的方法是接受用户输入并创建一个新的 Word 对象,然后使用 tree.search 函数是 BST 来查找单词,但这不是查找单词。我不确定我是否应该从用户输入创建一个新的 Word 对象,所以我认为我的错误就在那里。
这是我的主要方法:
public static void search( BST tree ){
Scanner input = new Scanner(System.in);
System.out.print("Search For: ");
Word searchWord = new Word(input.next());
if ( tree.search(searchWord) == null ){
System.out.println("Value was not found.");
}else{
System.out.println(searchWord.getFrequency());
}
}
这是我的 Word 课:
public class Word {
private String word;
private int frequency;
public Word( String w, int f ){
word = w;
frequency = f;
}
public Word( String w ){
word = w;
}
public void increment(){
frequency++;
}
public String getWord(){
return word;
}
public int getFrequency(){
return frequency;
}
public int compareTo(Word w){
return word.compareTo( w.getWord() );
}
@Override
public String toString(){
return word +" "+ frequency;
}
}
这是我的 BST 搜索算法:
public Node search( Word w ){
if ( root == null ){
System.out.println("No items to search.");
return null;
}else{
return search(w,root);
}
}
private Node search( Word w, Node n){
if ( w == n.getData() ){
return n;
}
if ( w.compareTo( n.getData() ) < 0 ){
if( n.getLeft() == null){
System.out.println("Item not found.");
return null;
}else{
return search(w, n.getLeft());
}
}else{
if ( n.getRight() == null ){
System.out.println("Item not found.");
return null;
}else{
return search(w, n.getRight());
}
}
}
【问题讨论】:
标签: java binary-search-tree frequency