我遍历树结构以收集叶节点的路径。您更喜欢哪种方式收集操作结果:
a) 合并 child 的结果并返回
private Collection<String> extractPaths(final Element element, final IPath parentPath) {
final IPath path = parentPath.append(element.getLabel());
final Collection<Element> children = getElementChildren(element);
if (children.isEmpty())
return Collections.singletonList(path.toString());
final Set<String> result = new TreeSet<String>();
for (final Element child : children)
result.addAll(extractPaths(child, path));
return result;
}
b) 提供结果集合作为参数并在每个递归步骤中添加新元素
private void extractPaths(final Element element, final IPath parentPath, final Set<String> result) {
final IPath path = parentPath.append(element.getLabel());
final Collection<Element> children = getElementChildren(element);
if (children.isEmpty())
result.add(path.toString());
for (final Element child : children)
extractPaths(child, path, result);
}
最佳答案
两者都可以毫无问题地使用。虽然,以前的解决方案更干净,因为它不会更改输入参数。没有副作用是函数式编程的本质。
关于java - 如何收集递归方法的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1142256/