import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* @Classname TreeTest
* @Description 树 结构的拼装
* @Date 2020/11/8 12:14
* @Author zhangjiahao
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class TreeTest {
private Integer keyId;
private Integer parentId;
private String name;
private List<TreeTest> children ;
private static Integer count =0 ;
public static void main(String[] args) {
List<TreeTest> initList = init();
//找出根父节点
List<TreeTest> topNode = initList.stream().filter(p -> p.getParentId() == 0).collect(Collectors.toList());
//找出叶子节点
List<TreeTest> childrenNode = initList.stream().filter(p -> p.getParentId() != 0).collect(Collectors.toList());
//递归执行
findChild(childrenNode,topNode);
//输出时间复杂度
System.out.println(count);
//输出结果 fastJson做解析器如果对象有重复会出现循环调用 显示出对象地址,加入序列化解决
System.out.println(JSON.toJSONString(builder().keyId(0).children(topNode).build(), SerializerFeature.DisableCircularReferenceDetect));
}
private static void findChild(List<TreeTest>childrenNode ,List<TreeTest> topNode){
//遍历根节点
topNode.forEach(p->{
//筛选如果子节点的parentId与父节点的id相等 则进入if分支
if(childrenNode.stream().anyMatch(t->t.getParentId().equals(p.getKeyId()))){
//筛选出当前父节点的儿子节点
List<TreeTest> collect = childrenNode.stream().filter(t -> t.getParentId().equals(p.getKeyId())).collect(Collectors.toList());
//计算时间复杂度
count++;
//为当前父节点添加儿子
collect.forEach(p.getChildren()::add);
}
//将当前的父节点的儿子节点 递归调用:其中,子节点还是所有子节点,当前父节点的儿子节点进入寻找子节点
findChild(childrenNode,p.getChildren());
});
}
private static List<TreeTest> init (){
List<TreeTest> allTree = new ArrayList<>(1);
TreeTest zjh = builder().keyId(1).name("zjh").parentId(0).children(new ArrayList<>()).build();
TreeTest fwh = builder().keyId(2).name("fwh").parentId(0).children(new ArrayList<>()).build();
TreeTest zzh = builder().keyId(3).name("zzh").parentId(0).children(new ArrayList<>()).build();
TreeTest zjh1 = builder().keyId(4).name("zjh2").parentId(1).children(new ArrayList<>()).build();
TreeTest fwh1 = builder().keyId(5).name("fwh2").parentId(2).children(new ArrayList<>()).build();
TreeTest zzh1 = builder().keyId(6).name("zzh2").parentId(3).children(new ArrayList<>()).build();
TreeTest zjh2 = builder().keyId(7).name("zjh3").parentId(4).children(new ArrayList<>()).build();
TreeTest fwh2 = builder().keyId(8).name("fwh3").parentId(5).children(new ArrayList<>()).build();
TreeTest fwh3 = builder().keyId(10).name("fwh3.1").parentId(5).children(new ArrayList<>()).build();
TreeTest zzh2 = builder().keyId(9).name("zzh3").parentId(6).children(new ArrayList<>()).build();
allTree.add(zjh);
allTree.add(zjh1);
allTree.add(zjh2);
allTree.add(fwh);
allTree.add(fwh1);
allTree.add(fwh2);
allTree.add(fwh3);
allTree.add(zzh);
allTree.add(zzh1);
allTree.add(zzh2);
return allTree;
}
}