liukangdong
2024-11-27 a856cfc04747d4d8f3605168531b253240d2e87c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package com.doumee.dao.business.vo;
 
import com.doumee.config.DataSyncConfig;
import com.doumee.core.utils.Constants;
import org.apache.commons.lang3.StringUtils;
 
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
 
/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Rk
 * @create 2023/7/13 10:40
 */
public class ProjectTree {
 
    // 保存参与构建树形的所有数据(通常数据库查询结果)
    public List<ProjectDataVO> nodeList = new ArrayList<>();
 
 
 
    /**
     *  构造方法
     *  @param nodeList 将数据集合赋值给nodeList,即所有数据作为所有节点。
     */
    public ProjectTree(List<ProjectDataVO> nodeList){
        this.nodeList = nodeList;
    }
 
 
    /**
     *   获取需构建的所有根节点(顶级节点) "0"
     *   @return 所有根节点List集合
     */
    public List<ProjectDataVO> getRootNode(){
        // 保存所有根节点(所有根节点的数据)
        List<ProjectDataVO> rootNodeList = new ArrayList<>();
        // treeNode:查询出的每一条数据(节点)
        for (ProjectDataVO treeNode : nodeList){
            if (Objects.isNull(treeNode.getPId()) && Constants.equalsInteger(treeNode.getLv(),Constants.ZERO)) {
                // 是,添加
                rootNodeList.add(treeNode);
            }
        }
        return rootNodeList;
    }
 
 
    /**
     *  根据每一个顶级节点(根节点)进行构建树形结构
     *  @return  构建整棵树
     */
    public List<ProjectDataVO> buildTree(){
        // treeNodes:保存一个顶级节点所构建出来的完整树形
        List<ProjectDataVO> treeNodes = new ArrayList<ProjectDataVO>();
        // getRootNode():获取所有的根节点
        for (ProjectDataVO treeRootNode : getRootNode()) {
            // 将顶级节点进行构建子树
            treeRootNode = buildChildTree(treeRootNode);
            // 完成一个顶级节点所构建的树形,增加进来
            treeNodes.add(treeRootNode);
        }
        return treeNodes;
    }
 
    /**
     *  递归-----构建子树形结构
     *  @param  pNode 根节点(顶级节点)
     *  @return 整棵树
     */
    public ProjectDataVO buildChildTree(ProjectDataVO pNode){
        List<ProjectDataVO> childTree = new ArrayList<ProjectDataVO>();
        // nodeList:所有节点集合(所有数据)
        for (ProjectDataVO treeNode : nodeList) {
            // 判断当前节点的父节点ID是否等于根节点的ID,即当前节点为其下的子节点
            if (!Objects.isNull(treeNode.getPId())
                    && Constants.equalsInteger(treeNode.getPId(),pNode.getId())
                    && Constants.equalsInteger((treeNode.getLv() -  1 ),pNode.getLv())
            ) {
                // 再递归进行判断当前节点的情况,调用自身方法
                childTree.add(buildChildTree(treeNode));
            }
        }
        // for循环结束,即节点下没有任何节点,树形构建结束,设置树结果
        pNode.setProjectDataVOList(childTree);
        return pNode;
    }
 
 
 
}