java递归生成树
1.获取数据
public List<TreeClassifyRespVO> getTreeClassifyList(ClassifyPageReqVO reqVO) {
List<ClassifyDO> classifyList = classifyMapper.selectList(reqVO);
List<TreeClassifyRespVO> childClassifyResp = ClassifyConvert.INSTANCE.convertList01(classifyList);
return getClassifyTree(childClassifyResp);
}
2.生成树形结构
public List<TreeClassifyRespVO> getClassifyTree(List<TreeClassifyRespVO> childClassifyResp) {
// 返回的树形数据
List<TreeClassifyRespVO> tree = new ArrayList<TreeClassifyRespVO>();
// 第一次遍历
for (TreeClassifyRespVO treeClassify : childClassifyResp) {
// 找到根节点,这里我的根节点的pid为0
if (treeClassify.getPid()==0) {
tree.add(findChild(treeClassify, childClassifyResp));
}
}
return tree;
}
3.查询子节点
private TreeClassifyRespVO findChild(TreeClassifyRespVO treeClassify, List<TreeClassifyRespVO> list) {
// 定义list用于存储子节点
List<TreeClassifyRespVO> children = new ArrayList<TreeClassifyRespVO>();
for (TreeClassifyRespVO node : list) {
// 找到根节点,这里我的根节点的pid为0
if (node.getPid().equals(treeClassify.getId())) {
// 调用递归
children.add(findChild(node, list));
}
}
treeClassify.setChildren(children);
return treeClassify;
}
4.效果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/97208ea333224b7ee2d1e37e4f1f6345.png#pic_center)