【问题标题】:Java tree, returning parent node recursivelyJava树,递归返回父节点
【发布时间】:2018-12-31 04:52:41
【问题描述】:

我正在处理一些关于从树中返回父节点的任务。
树看起来像这样:

      1
     / \
    2   3
   /    /
  4    5
      / \
     6   7

它有一些限制,即类节点没有可以返回父节点的方法。所以我们需要创建自己的方法来获取父节点。这是我的方法:

public Node getParentNode(int idChild, Node pParent) {
    List<Node> child;
    List<Node> gChild;
    if (pParent == null)
    {
        child = root.getChildren();
    } else {
        child = pParent.getChildren();
    }
    Node nParent = null;

    if (child != null) {
        for (Node c : child) {
            if (c.getId() == idChild) {
                nParent = c;
                break;
            } else {
                return getParentNode(idChild, c);
            }
        }
    }

    return nParent;
}

它以某种方式检索 id 为 4 的节点的父节点,即 id 为 2 的节点。但是当检索 id 为 5、6 和 7 的节点的父节点时,它不起作用。所以基本上它只适用于 id 为 2、3 和 4 的节点。

有人能指出我在递归或循环中遗漏了什么吗?因为我不是很擅长。

【问题讨论】:

  • 能否扩展Node类以保持对父节点的引用?
  • 好奇:gChild = c.getChildren();的意义何在? else {/*do nothing*/} 有什么意义?
  • 您尝试做的应该是“深度优先搜索”。您需要某种堆栈,否则它将无法正常工作。尝试在网上查找一些算法来做这个问题。
  • @HongyuWang 代码“深度优先搜索”。该代码使用 is “某种堆栈”的递归。或许你应该在评论之前看看代码。
  • @Andreas 那是个错误,已经删除了。说句公道话,就是突然想用java做的题,我没有编译器,网上编译一下就行了

标签: java loops recursion tree


【解决方案1】:

问题来了

return getParentNode(idChild, c);

您不应该只返回这个调用的结果。如果您要搜索的节点不在该子树中怎么办。只有当它返回非空结果时才应该返回(否则 for 循环不会循环到下一个子节点)

只有在递归调用中找到父节点时才返回。

另外,if 块中的 return 语句存在错误。您应该返回对父节点​​而不是当前子节点的引用。

 {
     ....
     if (child != null) {
         for (Node c : child) {
            gChild = c.getChildren(); //Btw this is just dead store
            if (c.getId() == idChild) {
                return pParent; //You want to return the parent not the current node.
            } else {
                nParent = getParentNode(idChild, c);
                if (nParent != null) {
                    return nParent;
                }
            }
        }
    }  
    return null; //Node (idChild) not found in this subtree
}

【讨论】:

  • 您还应该修复第一部分,即将nParent = c;替换为return pParent,并将return nParent;替换为return null;
猜你喜欢
  • 1970-01-01
  • 2018-10-31
  • 2023-04-07
  • 1970-01-01
  • 2014-08-12
  • 2015-03-25
  • 2017-07-25
  • 1970-01-01
  • 2017-09-26
相关资源
最近更新 更多