前言
最近遇到一个显示树结构的问题,需要将结果以树的形式进行展示,想着这个东西其实很普遍很常见,所以在网上找了两个方法+自己想的一个笨办法,现此进行简单思路说明总结。
参考链接
- https://blog.youkuaiyun.com/ldllovegyh/article/details/102692948
- https://blog.youkuaiyun.com/weixin_39819191/article/details/84180652?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase
实现方法
给定的Dept类实例如下图所示,以下方法以图中Dept实例为例。Dept属性分别为id、name、pid,根据pid锁定其父节点
public class Dept {
private Long id;
private Long parentId;
private String name;
}
Dept dept1 = new Dept(1L,0L,"IT");
Dept dept2 = new Dept(2L,1L,"code");
Dept dept3 = new Dept(3L,1L,"design");
Dept dept4 = new Dept(4L,0L,"ceo");
Dept dept5 = new Dept(5L,4L,"manager");
Dept dept6 = new Dept(6L,3L,"ui");
Dept dept7 = new Dept(7L,0L,"hr");
基本思路是定义一个树结构,然后对这个树结构重排列实现以pid为线索的父子节点关联。(关键属性在于List<DeptTree> childTree,通过递归生成树的方法不断将子节点加入到这个List中)
public class DeptTree {
private Long id;
private String name;