第一步:新建treenode

 

 

@Data
@ApiModel(value = "树形节点")
public class TreeNode {
@ApiModelProperty(value = "当前节点id")
protected int id;
@ApiModelProperty(value = "父节点id")
protected int parentId;
@ApiModelProperty(value = "子节点列表")
protected List<TreeNode> children = new ArrayList<TreeNode>();

public void add(TreeNode node) {
children.add(node);
}
}

第二步:查到所有的列  排序好

 

第三步:循环所有的列  再循环找每列的子集children set给这列(idpartenid)

/**
* 使用递归方法建树
*
* @param treeNodes
* @return
*/
public <T extends TreeNode> List<T> buildByRecursive(List<T> treeNodes, Object root) {
List<T> trees = new ArrayList<T>();
for (T treeNode : treeNodes) {
if (root.equals(treeNode.getParentId())) {
trees.add(findChildren(treeNode, treeNodes));
}
}
return trees;
}

/**
* 递归查找子节点
*
* @param treeNodes
* @return
*/
public <T extends TreeNode> T findChildren(T treeNode, List<T> treeNodes) {
for (T it : treeNodes) {
if (treeNode.getId() == it.getParentId()) {
if (treeNode.getChildren() == null) {
treeNode.setChildren(new ArrayList<>());
}
treeNode.add(findChildren(it, treeNodes));
}
}
return treeNode;
}

 

 

 

第三步