网站建设300,seo 网站推广,阿里云网站建设素材,淮南人才网目录 一、前言二、具体实现及拓展2.1、递归-目标节点到根节点的路径数据2.2、list转换为tree结构2.3、tree转换为list结构 一、前言
这么多年工作经历中#xff0c;“数据结构和算法”真的是超重要#xff0c;工作中很多业务都能抽象成某种数据结构问题。下面是项目中遇到的… 目录 一、前言二、具体实现及拓展2.1、递归-目标节点到根节点的路径数据2.2、list转换为tree结构2.3、tree转换为list结构 一、前言
这么多年工作经历中“数据结构和算法”真的是超重要工作中很多业务都能抽象成某种数据结构问题。下面是项目中遇到的一个问题。 业务背景 在一个复杂的N叉树目录上通过模糊搜索只返回搜索到的【要返回完整的从root到目标节点】节点链路以便外围系统直接使用 分析 按照实际操作模糊搜索只能搜索到需要的几个目标节点数据但实际业务需要的是这些目标节点到根节点的结构以便完美展示。
问题抽象 N叉树中找到所有目标节点到根节点的数据并构建成tree结构返回。如下图要返回这些目标节点到根节点的整个路径上的节点数据。
二、具体实现及拓展
完整的代码如下 public void filterNodeFromTree(){//查询所有的【有树形结构的】列表数据ListNodeTreeDo originList new ArrayList();MapString,NodeTreeDo originMap originList.stream().collect(Collectors.toMap(NodeTreeDo::getId,ma-ma));//目标节点idListString targetIds new ArrayList();SetString curRootIdSet new HashSet(); //收集某个目标节点到root的路径经过的所有节点for(String id : targetIds){if(curRootIdSet.contains(id)) continue;//已经经历过路径跳过curRootIdSet.addAll(collectNeedNode(originMap,id));}//收集到所有需要的节点的id然后在过滤多余的ListNodeTreeDo needList originList.stream().filter(k-curRootIdSet.contains(k.getId())).collect(Collectors.toList());//构建成treelistToTree(needList);}2.1、递归-目标节点到根节点的路径数据
private SetString collectNeedNode(MapString,NodeTreeDo originMap,String targetId){SetString idResultSet new HashSet();collectNeedNode(originMap,targetId,idResultSet);return idResultSet;}private boolean collectNeedNode(MapString,NodeTreeDo originMap,String targetId,SetString idSet){if(!originMap.containsKey(targetId)) return false;idSet.add(targetId);NodeTreeDo cur originMap.get(targetId);return collectNeedNode(originMap,cur.getParentId(),idSet);}
2.2、list转换为tree结构 private ListNodeTreeDo listToTree(ListNodeTreeDo originList){MapString, ListNodeTreeDo nodeByPidMap originList.stream().collect(Collectors.groupingBy(NodeTreeDo::getParentId));// 循环一次设置当前节点的子节点originList.forEach(node - node.setChildren(nodeByPidMap.get(node.getId())));// 获取 一级列表return originList.stream().filter(k-.equals(k.getParentId())).collect(Collectors.toList());}2.3、tree转换为list结构 private ListNodeTreeDo treeToList(ListNodeTreeDo treeList){ListNodeTreeDo resultList new ArrayList();for(NodeTreeDo node : treeList){getAllListFromChildren(node,resultList);}return resultList;}private void getAllListFromChildren(NodeTreeDo node,ListNodeTreeDo resultList){NodeTreeDo copy CommonUtil.transForm(node,NodeTreeDo.class);copy.setChildren(null); //深度拷贝后把children设置为nullresultList.add(copy);if(CollectionUtils.isNotEmpty(node.getChildren())){for(NodeTreeDo temp : node.getChildren()){getAllListFromChildren(temp,resultList);}}//没子节点了自动会退出}