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.效果