【问题标题】:Iterating over n-depth in tree like structure在树状结构中迭代 n 深度
【发布时间】:2018-12-24 17:28:10
【问题描述】:

如何以编程方式在树状结构上获取 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);
            });
        });
    });
});

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

【问题讨论】:

    标签: java tree iterator


    【解决方案1】:

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

    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
        }));
    }
    

    【讨论】:

      猜你喜欢
      • 2012-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-27
      • 2016-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多