聊这个话题之前,我们先聊聊什么是树形结构和递归
树形结构:
像这种带分支的有父子关系的结构就是树形结构;
既然聊起了树形结构,就不得不说数据结构中的** ‘树’ ** ;
让我们看一下数据结构中** 树 ** 的概念:
** 在计算器科学中,树(英语:tree)是一种抽象数据类型或是实现这种抽象数据类型的数据结构,用来模拟具有树状结构性质的数据集合。它是由n(n>0)个有限节点组成一个具有层次关系的集合。把它叫做“树”是因为它看起来像一棵倒挂的树,也就是说它是根朝上,而叶朝下的。它具有以下的特点:**
- 每个节点有零个或多个子节点;
- 没有父节点的节点称为根节点;
- 每一个非根节点有且只有一个父节点;
- 除了根节点外,每个子节点可以分为多个不相交的子树;
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-f6BJLagU-1627306852938)(/open.file/download?fileNo=488)]
我们就先了解这么多,下边再说说递归是什么意思: 程序调用自身的编程技巧称为递归
一般来说,在计算机语言中,对于一个函数,自己调用自己就是递归,概念好理解,也很简单,但是真正想要把递归用起来却并没有呢么简单,因为有的时候我们并不明白递归的数据到底是怎么走的,我们只是简单的知道这个概念,却并不知道递归的解空间是什么样子的。
下边呢,就我们知识管理系统部门树形结构的例子,给大家讲解一下递归的调用:
首先给大家看一下部门实体的结构:
public class DeptEntity {
private String deptid;
private String deptname;
private String Ext1;
private String description;
private Integer insertUser;
private Timestamp insertDatetime;
private Integer updateUser;
private Timestamp updateDatetime;
private Integer deleteFlag;
private String parentdeptid;
private List<DeptEntity> childDeptList;
private boolean parentis;
实体的树形结构初始化呢,最主要的属性就是实体ID,父实体ID,子实体集合;
大体上来说,分三个步骤:
- ** 创建本地数据集合 **
- **写递归函数 **
- **初始化根级数据集合,并循环调用递归函数 **
1、创建本地数据集合:
// 所有的部门数据--为树结构使用备份
private List<DeptEntity> deptEntitieList=new ArrayList<>();
//根部门
private List<DeptEntity> rootDeptList=new ArrayList<>();
2、 写递归函数:
// 递归 添加树函数
// 具体 实现思想,循环遍历所有的部门,然后循环,如果循环单体部门的父id等于传入的部门的id,那么该循环单体就是传入部门的子,就将其添加
// 到传入参数的实体子集合中,然后再去递归查询该循环单体的子集合;
public void getDeptEntitieTree(DeptEntity deptEntity){
List<DeptEntity> childDept = new ArrayList<>();
this.deptEntitieList.forEach(deptEntity1 -> {
if (org.apache.commons.lang.StringUtils.equals(deptEntity1.getParentdeptid(),deptEntity.getDeptid())){
childDept.add(deptEntity1);
getDeptEntitieTree(deptEntity1);
deptEntity.setChildDeptList(childDept);
}
});
}
3、初始化根级数据集合,并循环调用递归函数
@Get
public Boundary getDeptByTree(){
DeptDao deptDao = DeptDao.get();
this.deptEntitieList=deptDao.getDeptAll();
//将根结构存储到对应的全局变量中;
deptEntitieList.forEach(deptEntity -> {
if (org.apache.commons.lang.StringUtils.equals(deptEntity.getParentdeptid(),"0")){
this.rootDeptList.add(deptEntity);
}
});
this.rootDeptList.forEach(rootDept->{
getDeptEntitieTree(rootDept);
});
System.out.println(this.rootDeptList);
return send(this.rootDeptList);
}
是不是很简单?下边我们就解空间来说一下递归的数据走向和流程:
递归是一种深度优先搜索策略:
对于这个树,如果以递归的流程来走的话,呢么他的流程是这样的:
A>B>D>I>K>I>D>B>E>J>E>B>F>B>A>C>G>L>G>M>O>M>G>C>H>N>P>N>H>C>A