public static void main(String[] args) {
List<Concept> concepts = new ArrayList<>();
concepts.add(new Concept(0, 0, "顶级"));
concepts.add(new Concept(1, 0, "顶级1"));
concepts.add(new Concept(2, 1, "第一级1"));
concepts.add(new Concept(3, 1, "第一级2"));
concepts.add(new Concept(4, 2, "第二级1"));
concepts.add(new Concept(5, 2, "第二级2"));
concepts.add(new Concept(6, 4, "第三级1"));
concepts.add(new Concept(7, 4, "第三级2"));
concepts.add(new Concept(8, 6, "第四级1"));
Concept root = buildTree(concepts, 0);
System.out.println(root);
}
public static Concept buildTree(List<Concept> concepts, int rootId) {
Map<Integer, Concept> conceptMap = new HashMap<>();
for (Concept concept : concepts) {
conceptMap.put(concept.id, concept);
}
Concept root = conceptMap.get(rootId);
for (Concept concept : concepts) {
if (concept.parentId != concept.id) { // Avoid self-parenting
Concept parent = conceptMap.get(concept.parentId);
if (parent != null) {
parent.children.add(concept);
}
}
}
return root;
}