本文主要是介绍java递归生成树型结构,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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为0if (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为0if (node.getPid().equals(treeClassify.getId())) {// 调用递归children.add(findChild(node, list));}}treeClassify.setChildren(children);return treeClassify;
}
4.效果
这篇关于java递归生成树型结构的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!