如何使用递归获取父级的所有子级,然后获取其子级

2024-05-04

问候:

我的 JSP Web 应用程序中有父事务的比喻。我将事务 ID 存储在数据库中,要求是显示父级的所有子级,然后显示父级子级的后续子级。实际上,这个父母及其孩子的列表永远不会超过 4 或 5 层,但我需要考虑到它可以比这更多层。

我尝试过这样做将递归如下:

private static void processChildrenTransactions(
    AllTremorTransactionsVO parentBean,
    ArrayList<AllTremorTransactionsVO> childCandidatesList )
{
  ArrayList<AllTremorTransactionsVO> childList =
      new ArrayList<AllTremorTransactionsVO>();

  for (AllTremorTransactionsVO childTransactions : childCandidatesList)
  {
    if (childTransactions.getParentGuid() != null)
    {
      if (childTransactions.getParentGuid().equals(parentBean.getTransactionGuid()))
      {
        childList.add(childTransactions);
      }
    }
  }

  for (AllTremorTransactionsVO allTremorTransactionsVO : childList)
  {
    processChildrenTransactions(allTremorTransactionsVO, childList);    
  }

  return;
}

这不起作用,当循环运行时会产生堆栈溢出。关于如何做到这一点的最佳想法有什么想法吗?


如果方法的参数不能立即解析,则可以使用深度递归(存在使堆栈爆炸的风险)。 IE。被调用方法的最终结果取决于方法本身的结果。伪:

Result process(Parent parent) {
    Result result = new Result();
    for (Child child : parent.getChildren()) {
        result.update(process(child));
    }
    return result;
}

这会导致代码等待update()直到知道结果并因此将其保留在堆栈中。并且它会随着每次方法调用而累积。

您可以优化它来使用尾递归 http://en.wikipedia.org/wiki/Tail_recursion而是使用可变结果对象作为参数:

void process(Parent parent, Result result) {
    for (Child child : parent.getChildren()) {
        result.update(child);
        process(child, result);
    }
}

这样一来update()可以立即执行,因为参数可以立即解析。只要调用后没有返回值或任何其他逻辑发生process(),运行时可以通过从堆栈中删除调用来优化它。另请参阅前面链接的有关尾递归的 wiki 文章和这个网站 http://danzig.jct.ac.il/java_class/recursion.html.

但是..您发布的代码似乎已经是尾递归的。所以问题出在其他地方。研究完你的代码后,看起来你正在迭代same孩子们每次。 IE。只有无限循环的方法。大概是if检查是假的和/或子项在其自己的父子树中具有反向引用。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用递归获取父级的所有子级,然后获取其子级 的相关文章

随机推荐