直接上代码
- 数据结构
- Java 代码
public class TreeNode implements Serializable {
/**
* No:
* @fieldName: serialVersionUID
* @fieldType: long
* @Description: TODO
*/
private static final long serialVersionUID = 1L;
private String id;
private String text;
private String pid;
private List<TreeNode> children = new ArrayList();
public TreeNode() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public List<TreeNode> getChildren() {
return children;
}
public void setChildren(List<TreeNode> children) {
this.children = children;
}
}
DAO层
@Select("SELECT id, `name` as \"text\", parent_id as \"pid\" FROM sys_office WHERE `parent_id`=#{pid}")
List<TreeNode> getOfficeChildrenList(@Param("pid") String pid);
@Select("SELECT id, `name` as \"text\", parent_id as \"pid\" FROM sys_office WHERE `id`=#{id}")
TreeNode getOfficeNode(@Param("id") String id);
Service层 递归函数
public TreeNode officeTree(String id) {
// 根据id获取节点对象
TreeNode node = dao.getOfficeNode(id);
// 查询id下的所有子节点
List<TreeNode> childTreeNodes = dao.getOfficeChildrenList(id);
// 遍历子节点
for (TreeNode child : childTreeNodes) {
TreeNode n = userTree(child.getId()); // 递归
node.getChildren().add(n);
}
return node;
}
结果:
{
"id": "1",
"text": "总部",
"pid": "0",
"children": [{
"id": "2",
"text": "研发部",
"pid": "1"
},
{
"id": "3",
"text": "运维部",
"pid": "1"
},
{
"id": "4",
"text": "综合部",
"pid": "1",
"children": [{
"id": "5",
"text": "科室03",
"pid": "4"
},
{
"id": "6",
"text": "科室01",
"pid": "4"
},
{
"id": "7",
"text": "科室02",
"pid": "4"
}]
}]
}