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")); List<Integer> targetIds = new ArrayList<>(); targetIds.add(3); targetIds.add(6); targetIds.add(8); Concept root = buildFocusedTree(concepts, targetIds); System.out.println(root); } public static Concept buildFocusedTree(List<Concept> concepts, List<Integer> targetIds) { Map<Integer, Concept> conceptMap = new HashMap<>(); Map<Integer, Concept> allParentsMap = new HashMap<>(); for (Concept concept : concepts) { conceptMap.put(concept.id, concept); } for (int targetId : targetIds) { Concept current = conceptMap.get(targetId); while (current != null && current.id != 0) { allParentsMap.put(current.id, current); current = conceptMap.get(current.parentId); } if (current != null && current.id == 0) { allParentsMap.put(current.id, current); } } for (Concept concept : allParentsMap.values()) { Concept parent = conceptMap.get(concept.parentId); if (parent != null && allParentsMap.containsKey(parent.id) && !parent.children.contains(concept) && (concept.getId() != 0)) { parent.children.add(concept); } } return conceptMap.get(0); }
构造树结构,已知若干个子节点的id,需要将子节点和它的父节点的数据构造成一棵树,没有的子节点不展示。
最新推荐文章于 2024-07-14 23:27:18 发布