为二叉搜索树编写插入方法

时间:2015-04-02 00:51:40

标签: java insert binary-search-tree

我正在尝试使用Java创建二进制搜索树的方法,最终能够创建一个单词参考报告。

我的问题是我无法正确编译insertItem方法。

else if(word.compareTo(r.item)){给出了一个指向r.item的编译器错误,并说它无法转换为字符串。我该怎么做才能解决这个问题?

public void insert(String word) {
    root = insertItem(root, word);
}

protected TreeNode insertItem(TreeNode r, String word) {
    //base case
    if (r==null) {
        new TreeNode(new WordRefs(word));
    }
    else if (word.compareTo(r.item)) {
        r.left = insertItem(r.left, word);
    } else {
        r.right = insertItem(r.right, word);
    }
    return r;
}

public class WordRefs {

    private String word;
    private LinkedList<Integer> lineNumbers;

    public WordRefs(String word) {
        this.word = word;
        lineNumbers = new LinkedList<>();
    }

    public void addLine(int lineNumber) {
        lineNumbers.add(lineNumber);
    }

    public String getWord() {
        return word;
    }

    public LinkedList<Integer> getLineNumbers() {
        return lineNumbers;
    }

    public String toString() {
        String result = word + ":";
        for (Integer ii : lineNumbers) {
            result += " " + ii;
        }
        return result;
    }
}

class TreeNode {
    WordRefs item;
    TreeNode left;
    TreeNode right;

    public TreeNode(WordRefs item) {
        this.item = item;
        this.left = this.right = null;
    }

    public TreeNode(WordRefs item, TreeNode left, TreeNode right) {
        this.item  = item;
        this.left  = left;
        this.right = right;
    }
}

1 个答案:

答案 0 :(得分:0)

你的插入函数应该是这样的,你必须使用WordReft的getWord()函数,它应该是&lt; = 0去左边和&gt; 0到右边

protected TreeNode insertItem(TreeNode r, String word) {
//base case
if(r==null){
 r =   new TreeNode(new WordRefs(word));
    }
else if(word.compareTo(r.item.getWord()) <= 0){
    r.left = insertItem(r.left, word);
}else{
    r.right = insertItem(r.right, word);
}
return r;
}