用java怎么把list集合转化为tree
时间: 2023-02-13 21:08:48 浏览: 68
在 Java 中可以使用递归的方式来将 List 集合转换为 Tree。
假设你已经有了一个包含节点信息的 List,每个节点都有一个唯一的 ID 和父节点 ID。
你可以使用递归函数来遍历这个 List,对于每个节点,如果它有父节点,就找到父节点并把它加入到父节点的子节点列表中。否则,就把它作为根节点。
下面是一个简单的例子,展示了如何将 List 转换为 Tree:
```
import java.util.List;
import java.util.ArrayList;
class Node {
int id;
int parentId;
List<Node> children;
public Node(int id, int parentId) {
this.id = id;
this.parentId = parentId;
this.children = new ArrayList<>();
}
}
class Tree {
Node root;
public Tree(List<Node> nodes) {
// 构建树
for (Node node : nodes) {
if (node.parentId == 0) {
// 当前节点是根节点
root = node;
} else {
// 找到父节点并把当前节点加入到父节点的子节点列表中
Node parent = findParent(root, node.parentId);
parent.children.add(node);
}
}
}
private Node findParent(Node node, int parentId) {
if (node.id == parentId) {
return node;
}
for (Node child : node.children) {
Node parent = findParent(child, parentId);
if (parent != null) {
return parent;
}
}
return null;
}
}
public class Main {
public static void main(String[] args) {
// 创建节点列表
List<Node> nodes = new ArrayList<>();
nodes.add(new Node(1, 0));
nodes.add(new Node(2, 1));
nodes.add(new Node(