利用递归封装树型结构
上代码话不多,全是干货
package com.liyongyun.www;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
/**
* @Description
* @Author hdt
* @Date 2021/12/14 10:13
*/
public class tree {
public static void main(String[] args) {
tree tree = new tree();
List<trees> root = tree.createTree(tree.createTreesList(), "root");
System.out.println(root);
}
private List<trees> createTreesList(){
List<trees> treesList =new ArrayList<>();
trees root = new trees("0", "root", "0");
treesList.add(root);
trees trees1 = new trees("1","0","1");
treesList.add(trees1);
trees trees2 = new trees("2","1","2");
treesList.add(trees2);
trees trees3 = new trees("3","1","3");
treesList.add(trees3);
trees trees4 = new trees("4","1","4");
treesList.add(trees4);
trees trees5 = new trees("5","0","5");
treesList.add(trees5);
trees trees6 = new trees("6","5","6");
treesList.add(trees6);
trees trees7 = new trees("7","5","7");
treesList.add(trees7);
trees trees8 = new trees("8","5","8");
treesList.add(trees8);
trees trees9 = new trees("9","5","9");
treesList.add(trees9);
return treesList;
}
}
遍历
private List<trees> createTree(List<trees> date,String id){
//先创建一个集合来装当前节点
List<trees> trees1=new ArrayList<>();
//遍历所有的数据
for (trees trees : date) {
//判断当前节点是哪些节点的父类id
if(id.equals(trees.getPid())){
//如果是需要往树上挂
trees1.add(trees);
//给当前节点的子节点赋值
trees.setChildren(createTree(date,trees.getId()));
}
}
return trees1;
}
总结,思想就是利用二叉树遍历的方法,把方法利用代码实现出来。