@Data
public class TreeNode {
private Integer id;
private Integer pid;
private String name;
private List<TreeNode> children;
public TreeNode(Integer id, Integer pid, String name) {
this.id = id;
this.pid = pid;
this.name = name;
}
}
@RestController
@RequestMapping("/Department")
public class testController {
@GetMapping("menu")
public Object menu(){
List<TreeNode> list = new ArrayList<TreeNode>();
list.add(new TreeNode(1, 0, "1"));
list.add(new TreeNode(2, 0, "2"));
list.add(new TreeNode(3, 2, "3"));
list.add(new TreeNode(4, 3, "4"));
list.add(new TreeNode(5, 4, "5"));
list.add(new TreeNode(6, 5, "6"));
List<TreeNode> treeList = new ArrayList<TreeNode>();
List<TreeNode> treeList1 = new ArrayList<TreeNode>();
List<TreeNode> treeList2 = new ArrayList<TreeNode>();
List<TreeNode> treeList3 = new ArrayList<TreeNode>();
treeList = toTree(list);
return treeList;
}
private static List<com.example.demo.TreeNode> listGetStree(List<com.example.demo.TreeNode> list) {
List<com.example.demo.TreeNode> treeList = new ArrayList<com.example.demo.TreeNode>();
for (com.example.demo.TreeNode tree : list) {
if (tree.getPid() == 0) {
treeList.add(tree);
}
for (com.example.demo.TreeNode treeNode : list) {
if (treeNode.getPid() == tree.getId()) {
if (tree.getChildren() == null) {
tree.setChildren(new ArrayList<com.example.demo.TreeNode>());
}
tree.getChildren().add(treeNode);
}
}
}
return treeList;
}
public static List<com.example.demo.TreeNode> listToTree(List<com.example.demo.TreeNode> list) {
List<com.example.demo.TreeNode> treeList = new ArrayList<com.example.demo.TreeNode>();
for (com.example.demo.TreeNode tree : list) {
if (tree.getPid() == 0) {
treeList.add(findChildren(tree, list));
}
}
return treeList;
}
private static com.example.demo.TreeNode findChildren(com.example.demo.TreeNode tree, List<com.example.demo.TreeNode> list) {
for (com.example.demo.TreeNode node : list) {
if (node.getPid() == tree.getId()) {
if (tree.getChildren() == null) {
tree.setChildren(new ArrayList<com.example.demo.TreeNode>());
}
tree.getChildren().add(findChildren(node, list));
}
}
return tree;
}
private static List<com.example.demo.TreeNode> toTree(List<com.example.demo.TreeNode> list) {
List<com.example.demo.TreeNode> treeList = new ArrayList<com.example.demo.TreeNode>();
for (com.example.demo.TreeNode tree : list) {
if (tree.getPid() == 0) {
treeList.add(tree);
}
}
for (com.example.demo.TreeNode tree : list) {
toTreeChildren(treeList, tree);
}
return treeList;
}
private static void toTreeChildren(List<com.example.demo.TreeNode> treeList, com.example.demo.TreeNode tree) {
for (com.example.demo.TreeNode node : treeList) {
if (tree.getPid() == node.getId()) {
if (node.getChildren() == null) {
node.setChildren(new ArrayList<com.example.demo.TreeNode>());
}
node.getChildren().add(tree);
}
if (node.getChildren() != null) {
toTreeChildren(node.getChildren(), tree);
}
}
}
}
输出结果