java无限级树生成算法,空间复杂度为O(2n)

生成树的一般算法为遍历集合,获取父类,再依次递归遍历集合获取其子类,这次的升级算法大致如此,但是在遍历之前先进行了一次分组,将所有父级id相同的分为一组,遍历父级时直接根据id从map中获取其子级,这样一来,就之遍历了n次,算上分组遍历的n次,时间复杂度仅为O(2n);

树工厂类:

/**
 * 树工厂类,用于生成树
 * @author xieshuang
 * @date 2019-08-08 10:43
 */
public class TreeFactory{

    int a;
    /**
     * 优化方案
     * 1.按照pid进行分组
     * @param treeNodes
     * @return
     */

    public Collection createTree(Collection treeNodes){
        a = 0;
        long l2 = System.currentTimeMillis();
        Map> collect = treeNodes.stream().collect(Collectors.groupingBy(T::getPid));
        System.out.println("第一次遍历花费:"+(System.currentTimeMillis()-l2));
        long l3 = System.currentTimeMillis();
        Collection treeNodeList = new ArrayList<>();
        List list;
        List list1 = collect.get(0);
        List list2 = collect.get(0L);
        if (list1==null){
            list = list2;
        }else {
            list = list1;
        }
        if (list!=null){
            for (T t : list) {
                treeNodeList.add(addChildNode(t, collect));
            }
        }
        System.out.println("第二次遍历花费:"+(System.currentTimeMillis()-l3));
        System.out.println("总共遍历了:"+a);
        return treeNodeList;
    }

    private T addChildNode(T treeNode, Map> collect){
        a++;
        List list = collect.get(treeNode.getId());
        if (list!=null){
            List treeNodeList = new ArrayList<>();
            for (T t : list) {
                treeNodeList.add(addChildNode(t, collect));
            }
            treeNode.setChilds(treeNodeList);
        }
        return treeNode;
    }

}

树父类:

@Data
public class Tree{
    private Number id;
    private Number pid;
    private Collection childs;
}

自定义的树类:

@Data
public class MyTree extends Tree {
    private String name;
}
public class TreeFactoryTest {

    public static void main(String[] args) {
        List trees = new ArrayList<>();
        for (int i = 1; i < 100; i++) {
            MyTree myTree = new MyTree();
            myTree.setName("顶级"+i);
            myTree.setId(i);
            myTree.setPid(0);
            trees.add(myTree);
            for (int j = 0; j <100 ; j++) {
                MyTree myTree1 = new MyTree();
                myTree1.setName("子级"+j);
                myTree1.setId(j+(i*100));
                myTree1.setPid(i);
                trees.add(myTree1);
                for (int k = 0; k <100 ; k++) {
                    MyTree myTree2 = new MyTree();
                    myTree2.setName("子级"+j);
                    myTree2.setId(k+(j*100)+(i*10000));
                    myTree2.setPid(j+(i*100));
                    trees.add(myTree2);
                }
            }
        }
        System.out.println(trees.size());
        Collection tree = new TreeFactory().createTree(trees);
        //System.out.println(JSONObject.toJSONString(tree));
    }
}

测试结果:

百万数据量耗时0.2秒

java无限级树生成算法,空间复杂度为O(2n)_第1张图片

你可能感兴趣的:(java算法)