1.java基础- java List 转 tree (树形结构
2021-08-20 本文已影响0人
那钱有着落吗
原理就是回调函数,迭代
public class TreeNode {
private String id;
private String pid;
private String name;
private List<TreeNode> children = new ArrayList<>();
public TreeNode() {
}
public TreeNode(String id, String pid, String name) {
this.id = id;
this.pid = pid;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<TreeNode> getChildren() {
return children;
}
public void setChildren(List<TreeNode> children) {
this.children = children;
}
}
private List<TreeNode> buildTree(List<TreeNode> nodeList){
List<TreeNode> result = new ArrayList<>();
for (TreeNode zone:nodeList) {
if (zone.getPid().equals("0")) {
result.add(zone);
setChildren(nodeList, zone);
}
}
return result;
}
public static void setChildren(List<TreeNode> list, TreeNode parent) {
for (TreeNode zone: list) {
if(parent.getId().equals(zone.getPid())){
parent.getChildren().add(zone);
}
}
if (parent.getChildren().isEmpty()) {
return;
}
for (TreeNode zone: parent.getChildren()) {
setChildren(list, zone);
}
}