BinarySearchTree 中的 search(String target) 方法

问题描述

我正在编写一个字典系统。这个系统应该是这样运行的;

  1. 用户输入一个他/她想了解定义的词。
  2. 单词和定义存储在链表中
  3. 搜索时我应该使用二叉搜索
  4. bst 正在比较单词
  5. search(String target) 方法应该返回单词+定义

问题:

  • 我已经在二叉搜索树中打印了链表,但是方法 search() 无法返回单词+定义?我哪里做错了?

public class BinarySearchTree {

private String data;
private BinarySearchTree left;
private BinarySearchTree right;

public BinarySearchTree() {
    // I've deleted the getters/setters
public void addNode(String data) {
    if (this.data == null) {
        this.data = data;
    } else {
        if (this.data.compareto(data)> 0) {
            if (this.left != null) {
                this.left.addNode(data);
            } else {
                this.left = new BinarySearchTree(data);
            }

        } else {
            if (this.right != null) {
                this.right.addNode(data);
            } else {
                this.right = new BinarySearchTree(data);
            } 
        }
    }
}
public boolean search(BinarySearchTree t,String key) {
    if (t.data.equals(key)) return true;

    if (t.left != null && search(t.left,key)) return true;

    if (t.right != null && search(t.right,key)) return true;

    return false;
}
}

public class Vocab {
public static void main(String args[]) 
{ 
    
    LinkedList<String> ll 
        = new LinkedList<>(); 
    Word word = new Word("Engineer","Mühendis");
    Word word2 = new Word("School"," Okul");
    Word word3 = new Word("Pencil","Kalem");
    Word word4 = new Word("Window","Pencere");
  
    ll.add(word.toString());
    ll.add(word2.toString());
    ll.add(word3.toString());
    ll.add(word4.toString());

    for (int i = 0; i < ll.size(); i++) { 

        System.out.println(ll.get(i)); 
    } 

    BinarySearchTree bst = new BinarySearchTree();
    // Using the for each loop 
    for (String str : ll) {         
        bst.addNode(str);
    }

    System.out.println("search: " );
    //here I want to return search() method and get the word+deFinition
    
}

}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)