【问题标题】:Java recursive method always returns nullJava递归方法总是返回null
【发布时间】:2017-01-16 14:12:23
【问题描述】:

我有一个二叉搜索树,我想获取具有特定值的子树,如下所示:

private Node getNode(Node root,Object c){

        String data = String.valueOf(c);
        if(root !=  null) {
            getNode(root.left,c);
            if(root.data.equals(data)){
                System.out.println("found!!");
                 return root;
              }
            getNode(root.right,c);
          }
        return null;
    }

System.out.println(getNode(root,c));

输出:

“找到了!!”

但它总是返回一个空值。我想知道为什么以及如何解决这个问题。谢谢!

【问题讨论】:

  • 使用调试器找出来。我的第一个猜测是,root 为空
  • 你对递归调用的返回值什么都不做,
  • 根不为空。
  • 您应该首先进行根数据检查,而不是在获得可能为空的左节点之后
  • 名为root的参数为null,此时你的方法返回null。您到达树的尽头并且没有返回其他值

标签: java recursion tree binary-search-tree


【解决方案1】:

您没有评估getNode(root.left, c)getNode(root.right, c) 返回的结果。

正确的是:

private Node getNode(Node root, Object c) {
    String datac = String.valueOf(c);
    if(root == null) return null;
    if(Objects.equals(datac, root.data)) return root;
    Node tmp;
    return ((tmp = getNode(root.left, c)) != null) ? tmp : getNode(root.right, c);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-12
    • 1970-01-01
    • 2014-11-13
    • 2020-08-16
    • 1970-01-01
    • 2021-05-03
    • 2016-07-10
    • 2016-02-10
    相关资源
    最近更新 更多