将具有多个值的地图转换为树?

时间:2009-08-08 23:50:19

标签: java algorithm data-structures tree hierarchy

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

示例数据集

  • NB 2 => {NC 2 ND 2 }
  • ND 1 => {NG 1 NH 1 }
  • NA 1 =&gt; {NB <子> 1 }
  • NB 1 =&gt; {NC 1 ND 1 NE 1 }
  • NA 2 =&gt; {NB的 <子> 2 的}
  • NC 1 =&gt; {NF <子> 1 }
  • NE 1 =&gt; {NI 1 NJ 1 NK 1 }

NA 1

的结果树
NA1
`-- NB1
    |-- NC1
    |   `-- NF1
    |-- ND1
    |   |-- NG1
    |   `-- NH1
    `-- NE1
        |-- NI1
        |-- NJ1
        `-- NK1

NA 2的结果树

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

2 个答案:

答案 0 :(得分:3)

我不知道任何会进行此转换的库方法。这是我怎么做的。这很简单,IMO。

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实例。

请注意我没有调试此代码: - )

答案 1 :(得分:0)

当你谈到将它们转换成一组树时,你是在谈论在内存中表示它们的方法吗?

或许我们可以通过算法来处理你的键和值集并将它们放入内存中的表示中?

或者您在谈论图形表示?