[英]Writing an insert method for a binary search tree
I'm trying to implement the methods to create a binary search tree in Java that will eventually be able to create a word-reference report. 我正在尝试实现在Java中创建二进制搜索树的方法,该方法最终将能够创建单词参考报告。
My problem is I can't get my insertItem
method to compile properly. 我的问题是我无法正确
insertItem
我的insertItem
方法。
The the line else if(word.compareTo(r.item)){
gives a compiler error that points to r.item
and says it cannot be converted to a string. else if(word.compareTo(r.item)){
给出了指向r.item
的编译器错误,并指出无法将其转换为字符串。 What should I do to solve this? 我该怎么做才能解决这个问题?
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;
}
}
your insert function should be something like this, you have to use the getWord() function from WordReft and it should be <= 0 to go to the left side and > 0 to go to the right 您的插入函数应该是这样的,您必须使用WordReft中的getWord()函数,并且它应该<= 0转到左侧,而> 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.