java 输出2n,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 CollectioncreateTree(CollectiontreeNodes){

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();

CollectiontreeNodeList = new ArrayList<>();

Listlist;

Listlist1 = collect.get(0);

Listlist2 = 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++;

Listlist = collect.get(treeNode.getId());

if (list!=null){

ListtreeNodeList = 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) {

Listtrees = 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());

Collectiontree = new TreeFactory().createTree(trees);

//System.out.println(JSONObject.toJSONString(tree));

}

}

测试结果:

百万数据量耗时0.2秒

51fbd84a1cc09f6b1ef95bf64e5345b9.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值