首页 > 解决方案 > Java树,递归返回父节点

问题描述

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

      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 的节点。

有人可以指出我在递归或循环中缺少什么吗?因为我不是很擅长。

标签: javaloopsrecursiontree

解决方案


问题就在这里

return getParentNode(idChild, c);

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

仅当您在递归调用中找到父节点时才返回。

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

 {
     ....
     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
}

推荐阅读