【问题标题】:Recursive method not stopping at base case in BST递归方法不在 BST 中的基本情况处停止
【发布时间】: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


    【解决方案1】:

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

    else 和您的递归调用之间添加return,例如:

    else return this.left.findPrefix(prefix);
    

    至于您的 NPE,在执行 null 检查之前,您将在您的方法中访问 leftright 的成员。也在那里进行空检查。

    【讨论】:

    • 谢谢!我会一直坚持下去
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-31
    • 1970-01-01
    • 1970-01-01
    • 2016-09-01
    • 1970-01-01
    • 2017-12-31
    • 2020-09-19
    相关资源
    最近更新 更多