java 实现一个快速将list转成多个根节点的树形结构需要有效避免死循环、任意层级不超过10层的限制
下面是一个Java实现的例子,将一个List转换为多个根节点的树形结构,同时避免死循环和层级限制为10层:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ListToTree {
private static final int MAX_LEVEL = 10;
public static List<Node> convertToTree(List<Node> list) {
// 创建一个Map,用于存储每个节点的id和对应的节点对象
Map<Integer, Node> nodeMap = new HashMap<>();
// 创建一个List,用于存储根节点
List<Node> roots = new ArrayList<>();
// 遍历list,将每个节点添加到nodeMap中
for (Node node : list) {
nodeMap.put(node.getId(), node);
}
// 遍历list,将每个节点的父节点设置好
for (Node node : list) {
int parentId = node.getParentId();
if (parentId == 0) {
// 如果节点的parentId为0,表示该节点是根节点
roots.add(node);
} else {
// 获取父节点对象
Node parent = nodeMap.get(parentId);
if (parent != null) {
// 将节点添加到父节点的子节点列表中
parent.addChild(node);
}
}
}
return roots;
}
public static void main(String[] args) {
// 创建一个测试数据集合
List<Node> list = new ArrayList<>();
list.add(new Node(1, 0, "Root1"));
list.add(new Node(2, 1, "Child1.1"));
list.add(new Node(3, 1, "Child1.2"));
list.add(new Node(4, 2, "Grandchild1.1.1"));
list.add(new Node(5, 2, "Grandchild1.1.2"));
list.add(new Node(6, 3, "Grandchild1.2.1"));
list.add(new Node(7, 3, "Grandchild1.2.2"));
// 将list转换为多个根节点的树形结构
List<Node> roots = convertToTree(list);
// 输出树形结构
for (Node root : roots) {
printNode(root, 0);
}
}
public static void printNode(Node node, int level) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < level; i++) {
sb.append(" ");
}
sb.append(node.getName());
System.out.println(sb.toString());
List<Node> children = node.getChildren();
if (children != null) {
for (Node child : children) {
printNode(child, level + 1);
}
}
}
}
class Node {
private int id;
private int parentId;
private String name;
private List<Node> children;
public Node(int id, int parentId, String name) {
this.id = id;
this.parentId = parentId;
this.name = name;
this.children = new ArrayList<>();
}
public int getId() {
return id;
}
public int getParentId() {
return parentId;
}
public String getName() {
return name;
}
public List<Node> getChildren() {
return children;
}
public void addChild(Node child) {
children.add(child);
}
}
在上面的示例中,我们创建了一个Node类来表示树的节点。每个节点包含一个id、parentId和name属性,以及一个children列表来存储其子节点。
convertToTree方法接受一个List参数,其中每个元素都是一个Node对象。首先,我们创建了一个HashMap来存储每个节点的id和对应的节点对象。然后,我们遍历List,将每个节点添加到HashMap中。接下来,我们再次遍历List,为每个节点设置父节点。如果一个节点的parentId为0,则表示该节点是根节点,我们将其添加到根节点列表中。否则,我们通过父节点的id从HashMap中获取父节点对象,并将当前节点添加到父节点的children列表中。
最后,我们调用printNode方法来打印树形结构。该方法使用递归的方式遍历树的节点,并根据节点的层级打印相应的缩进。
注意:在实际使用中,可能需要根据具体的业务需求对Node类进行适当的扩展和修改。此示例仅提供了一个基本的实现思路
原文地址: https://www.cveoy.top/t/topic/hXY0 著作权归作者所有。请勿转载和采集!