在BST中不在基本情况下停止的递归方法

时间:2015-11-17 23:58:56

标签: java recursion binary-search-tree

我写了一个方法到达基本情况(我可以告诉因为它打印了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

1 个答案:

答案 0 :(得分:0)

您的方法在基本情况下停止,但之前的递归调用忽略了它返回的内容。

return和您的递归通话之间添加else,例如:

else return this.left.findPrefix(prefix);

对于您的NPE,您在执行left检查之前,正在访问您方法中的rightnull成员。在那里也无需检查。