gpt4 book ai didi

java - 在树状结构中迭代 n 深度

转载 作者:太空宇宙 更新时间:2023-11-04 09:57:41 28 4
gpt4 key购买 nike

如何以编程方式在树状结构上获取 n 深度迭代器?在根目录中我有

List<Node>

每个节点有

Map<Integer,List<Node>> 

n+1 深度。

我已修复 1 个深度:

// DEPTH 1
nodeData.forEach(baseNode -> {
baseNode.getChildNodes().entrySet().forEach(baseNodeChildeNodes -> {
genCombOnePass(baseNodeChildeNodes, 2);
});
});

// DEPTH 2
nodeData.forEach(baseNode -> {
baseNode.getChildNodes().entrySet().forEach(baseNodeChildeNodes -> {
baseNodeChildeNodes.getValue().forEach(childNodeEs -> {
childNodeEs.getChildNodes().entrySet().forEach(childNode -> {
genCombOnePass(childNode, 3);
});
});
});
});

但我需要迭代前。 1-9 深度。

最佳答案

您需要某种递归函数来实现您想要的:

static void depthTraversal(Node root, int depth, int maxDepth) {
if (depth == maxDepth) { // if you reached max level - exit
return;
}
if (root == null || root.getChildNodes() == null) { // if you reached null child - exit
return;
}
root.getChildNodes().forEach((key, value) -> value.forEach(node -> {
// do what you need with your nodes
depthTraversal(node, depth + 1, maxDepth); // recursively go to next level
}));
}

关于java - 在树状结构中迭代 n 深度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53911366/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com