从给定的HashMap构造树

时间:2018-04-17 20:33:15

标签: java loops

我想遍历HashMap<Integer, ArrayList<Integer>> map并从此地图构建树。例如,我有以下地图:1 = [2,3],2 = [3,4],3 = [1,5],4 = [2,5],5 = [1,4]。我想要做的是以下面的方式遍历这个地图:

public static Tree getTree (HashMap<Integer, ArrayList<Integer>> paths) {

    Tree<Integer> tree = new Tree(-1);
    Integer node;

    for (int i = 1; i <= paths.size(); i++) {

        for (int j = 0; j < paths.get(i).size(); j++) {

            node = paths.get(i).get(j);
            tree.addLeaf(i, node);

            for(int k = 0; k < paths.get(node).size(); k++) {

                tree.addLeaf(node, paths.get(node).get(k));
                node = paths.get(node).get(k);

                // now I have to go to paths.get(node) and receive its ArrayList

                for (int t = 0; t < paths.get(node).size(); t++) {

                      tree.addLeaf(node, paths.get(node).get(t));
                      node = paths.get(node).get(t);


                }

            }
        }
    }

    return tree;
}

如果新节点等于其祖先之一,则应将该节点添加到树中,但不应再遍历该节点。我想动态地进行这个操作。

1 个答案:

答案 0 :(得分:1)

使用递归遍历map,将当前状态作为参数传递给递归方法:

public void step(Map<Integer, List<Integer>> tree, List<Integer> nodes, Integer key) {
    if (nodes.contains(key)) {
        // skip node which we already processed
        return;
    }
    nodes.add(key);

    List<Integer> children = tree.get(key);
    // add sanity checks here if you expect inconsistent data
    for (Integer child : children) {
        step(tree, nodes, child);
    }
}

现在最困难的部分是找到哪个节点是root。由于您使用地图,因此没有地图条目的顺序。所以我把这部分留给你了:

step(map, tempList, 1);