微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

BinarySearchTree 中的 search(String target) 方法

如何解决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 举报,一经查实,本站将立刻删除。