有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

具有多个值的java转换映射到树?

给定一组随机分布的键,每个键映射到一组值,如何将其转换为多棵树

示例数据集

  • 注意;{NC2ND2}
  • ND1=>;{NG1NH1}
  • NA1=>;{NB1}
  • 注意:1;{NC1ND1NE1}
  • NA2=>;{NB2}
  • NC1=>;{NF1}
  • NE1=>;{NI1NJ1NK1}

NA1的结果树

NA1
`-- NB1
    |-- NC1
    |   `-- NF1
    |-- ND1
    |   |-- NG1
    |   `-- NH1
    `-- NE1
        |-- NI1
        |-- NJ1
        `-- NK1

NA2的结果树

NA2
`-- NB2
    |-- NC2
    `-- ND2

共 (1) 个答案

  1. # 1 楼答案

    我不知道有任何库方法可以进行这种转换。我会这么做的。这很简单,依我看

    public class Tree {
        public Tree(String key) {
            // ...
        }
        public void addChild(Tree child) {
            // ...
        }
    }
    
    public Set<Tree> transform(Map<String, List<String>> input) {
        // Potential tree roots.  We start with all LHS keys as potential roots,
        // and eliminate them when we see their keys on the RHS.
        Set<String> roots = new HashSet<String>(input.keySet());
    
        // This map associates keys with the tree nodes that we create for them
        Map<String, Tree> map = new HashMap<String, Tree>();
    
        for (Map.Entry<String, List<String>> entry : input.entrySet()) {
            String key = entry.getKey();
            List<String> childKeys = entry.getValue();
            Tree tree = map.get(key);
            if (tree == null) {
                tree = new Tree(key);
                map.put(key, tree);
            }
            for (String childKey : childKeys) {
                roots.remove(childKey);
                Tree child = map.get(childKey);
                if (child == null) {
                    child = new Tree(childKey);
                    map.put(childKey, child);
                }
                tree.addChild(child);
            }
        }
        Set<Tree> res = new HashSet<Tree>(roots.size());
        for (String key : roots) {
            res.add(map.get(key));
        }
        return res;
    }
    

    编辑:注意,如果输入代表一组DAG(有向无环图),该算法将“起作用”。然而,我刚刚意识到,生成的一组树共享输入数据中任何公共子树的TreeNode实例

    请注意,我尚未调试此代码:-)