【发布时间】:2015-11-17 23:58:55
【问题描述】:
我编写了一个达到基本情况的方法(我可以说是因为它打印了 print 语句),但它随后循环返回并返回 null(在方法的末尾)。为什么我的方法没有停留在基本情况?
编辑:另外,如果我的 BST 中不存在一个对象,它不会返回 null。我得到一个空指针异常,因为 if (this.left == null) return null; 或 if (this.right == null) return null; 语句不应该发生这种情况
public MovieInfo findPrefix(String prefix) {
String key = prefix.substring(0, prefix.length() - 1);
System.out.println("PREFIX: " + prefix + " KEY: " + key + " THIS.KEY: " + this.key);
System.out.println("PARENT: " + this.data.shortName + " LEFT: " + this.left.data.shortName + " RIGHT: " + this.right.data.shortName);
System.out.println();
if (compare(key, this.key)) {
System.out.println(this.data.ID + " " + this.data.shortName + " " + this.data.fullName + " " + i);
return this.data;
}
else if (key.compareToIgnoreCase(this.key) < 0) {
if (this.left == null) return null;
else this.left.findPrefix(prefix);
}else if (key.compareToIgnoreCase(this.key) > 0) {
if (this.right == null) return null;
else this.right.findPrefix(prefix);
}
return null;
}//return the data element MovieInfo where the shortName starts with the prefix
【问题讨论】:
标签: java recursion binary-search-tree