给出随机布设的钥匙,跟每个关键映的价值,你会怎么变换成多种树吗?

例的数据集

  • NB的2 =>{NC2 ND2}
  • ND1 =>{NG1 NH1}
  • NA1 =>{NB1}
  • NB的1 =>{NC1 ND1 NE1}
  • NA2 =>{NB2}
  • NC1 =>{NF1}
  • NE1 =>{NI1 新泽西1 NK1}

得到的树娜1

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

得到的树娜2

NA2
`-- NB2
    |-- NC2
    `-- ND2
有帮助吗?

解决方案

我不知道有任何库的方法,将做到这一点的转变。这里是我怎么会这样做。这是很简单,国际海事组织。

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(向非循环的图表).然而,我刚刚意识到,所产生的一套树 分享树节点实例对于任何共同的子树在输入数据。

小心,我还没有调试这个代码:-)

其他提示

当你谈论它们转化成一套树,你们在谈论的方法表示他们的记忆?

或者也许是的算法我们会走你的组键的和价值观,并把它们纳入在内存表?

或是你在谈论一个图形表示?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top