JAVA-Construa recursivamente uma estrutura de árvore com nós filhos aninhados e retorne parâmetros para o front end&& Obtenha todos os nós folha sob um determinado nó&& Obtenha os nós folha sob um determinado nó (nós sem nós filhos)


No projeto JAVA, uma estrutura de árvore é construída recursivamente com base no parentId, e seus subnós filhos são aninhados e retornados ao front-end. Obtenha todos os nós folha sob um determinado nó raiz; obtenha nós folha (nós sem nós filhos) sob um determinado nó raiz; obtenha apenas o ID do nó folha.

Construir árvore

tagId é o id do nó; parentId é o id do nó pai; tagName é o nome do nó; children é o tipo de lista do nó filho.

getRootNode() é obter todos os nós raiz. Determinamos o ID do nó pai (parentId) como 0 como o nó raiz.

buildChildTree() obtém o conjunto de todos os nós e determina se o ID do nó pai (parentId) do nó atual é igual ao ID (tagId) do nó raiz, ou seja, o nó atual é seu nó filho. Em seguida, determine recursivamente a situação do nó atual e chame seu próprio método.

buildTree() constrói uma estrutura de árvore baseada em cada nó raiz.

    /**
     *   获取需构建的所有根节点(顶级节点) "0"
     *   @return 所有根节点List集合
     */
    public List<TagRequestVO> getRootNode(){
    
    chre
        // 保存所有根节点(所有根节点的数据)
        List<TagRequestVO> rootNodeList = new ArrayList<>();
        // treeNode:查询出的每一条数据(节点)
        List<Tag> nodeList = tagMapper.selectList(null);
        for (Tag treeNode : nodeList){
    
    
            // 判断当前节点是否为根节点,
            if (treeNode.getParentId().equals("0")) {
    
    
                // 是,添加
                //tagId为节点id;parentId为其父节点id;tagName为节点名称
                TagRequestVO response = new TagRequestVO();
                response.setTagId(treeNode.getTagId());
                response.setTagName(treeNode.getTagName());
                response.setParentId(treeNode.getParentId());
                rootNodeList.add(response);
            }
        }
        return rootNodeList;
    }

    /**
     *  递归-----构建子树形结构
     *  @param  pNode 根节点(顶级节点)
     *  @return 整棵树
     */
    public TagRequestVO buildChildTree(TagRequestVO pNode){
    
    
        List<TagRequestVO> childTree = new ArrayList<>();
        // nodeList:所有节点集合(所有数据)
        List<Tag> nodeList = tagMapper.selectList(null);
        for (Tag treeNode : nodeList) {
    
    
            // 判断当前节点的父节点ID是否等于根节点的ID,即当前节点为其下的子节点
            //tagId为节点id;parentId为其父节点id;tagName为节点名称
            if (treeNode.getParentId().equals(pNode.getTagId())) {
    
    
                // 再递归进行判断当前节点的情况,调用自身方法
                TagRequestVO response = new TagRequestVO();
                response.setTagId(treeNode.getTagId());
                response.setTagName(treeNode.getTagName());
                response.setParentId(treeNode.getParentId());
                childTree.add(buildChildTree(response));
            }
        }
        // for循环结束,即节点下没有任何节点,树形构建结束,设置树结果
        pNode.setChildren(childTree);
        return pNode;
    }

	/**
     *  根据每一个顶级节点(根节点)进行构建树形结构
     *  @return  构建整棵树
     */
    public List<TagRequestVO> buildTree(){
    
    
        // treeNodes:保存一个顶级节点所构建出来的完整树形
        List<TagRequestVO> treeNodes = new ArrayList<>();
        // getRootNode():获取所有的根节点
        for (TagRequestVO treeRootNode : getRootNode()) {
    
    
            // 将顶级节点进行构建子树
            treeRootNode = buildChildTree(treeRootNode);
            // 完成一个顶级节点所构建的树形,增加进来
            treeNodes.add(treeRootNode);
        }
        return treeNodes;
    }

Os filhos retornarão um array vazio [] quando não houver nós filhos; se você quiser não se arrepender quando estiver vazio, você pode adicionar um comentário ao VO e ele não retornará.

//为空不返回
@JsonInclude(JsonInclude.Include.NON_EMPTY)
//为null不返回
@JsonInclude(JsonInclude.Include.NON_NULL)

Obtenha todos os nós folha em um nó

A construção da árvore não é muito diferente da anterior, exceto que o ID do nó (tagId) necessário para a filtragem especificada precisa ser adicionado à função de obtenção do nó raiz (getRootNodeByTag()). A estrutura da subárvore (buildChildTreeByTag()) é exatamente igual à anterior. Depois de construir a árvore, combine os nós folha abaixo dela.

getAllChildren() obtém todos os seus nós folha.

getTreeTagId() obtém todos os IDs de seus nós folha (tagId).

	/**
     *   获取需构建的根节点,根据根节点tagId匹配
     *   @return 所有根节点List集合
     */
    public List<TagRequestVO> getRootNodeByTag(String tagId){
    
    
        QueryWrapper<Tag> wrapper = new QueryWrapper<>();
        wrapper.and(w -> w.eq("tag_id", tagId).or().eq("parent_id", tagId));
        List<Tag> nodeList = tagMapper.selectList(wrapper);
        List<TagRequestVO> rootNodeList = new ArrayList<>();
        for (Tag treeNode : nodeList){
    
    
            TagRequestVO response = new TagRequestVO();
            if (treeNode.getParentId().equals("0")) {
    
    
                response.setTagId(treeNode.getTagId());
                rootNodeList.add(response);
            }
        }
        return rootNodeList;
    }

	/**
     *  递归-----构建子树形结构
     *  @param  pNode 根节点(顶级节点)
     *  @return 整棵树
     */
    public TagRequestVO buildChildTreeByTag(TagRequestVO pNode){
    
    
        List<TagRequestVO> childTree = new ArrayList<>();
        List<Tag> nodeList = tagMapper.selectList(null);
        for (Tag treeNode : nodeList) {
    
    
            if (treeNode.getParentId().equals(pNode.getTagId())) {
    
    
                TagRequestVO response = new TagRequestVO();
                response.setTagId(treeNode.getTagId());
                response.setParentId(treeNode.getParentId());
                childTree.add(buildChildTreeByTag(response));
            }
        }
        pNode.setChildren(childTree);
        return pNode;
    }

	/**
     *  根据每一个顶级节点(根节点)进行构建树形结构
     *  @return  构建整棵树
     */
    public List<TagRequestVO> buildTreeByTag(String tagId){
    
    
        List<TagRequestVO> treeNodes = new ArrayList<>();
        for (TagRequestVO treeRootNode : getRootNodeByTag(tagId)) {
    
    
            treeRootNode = buildChildTreeByTag(treeRootNode);
            treeNodes.add(treeRootNode);
        }
        return treeNodes;
    }

	//获取该节点下的所有叶子节点
    private List<TagRequestVO> getAllChildren(TagRequestVO tagRequestVO,List returnList){
    
    
    	//获取叶子节点children
        List<TagRequestVO> childrenList = tagRequestVO.getChildren();
        if(childrenList!=null && childrenList.size()>0){
    
    
            for(TagRequestVO children : childrenList){
    
    
            	//递归
                getAllChildren(children,returnList);
                returnList.add(children);
            }
        }
        return returnList;
    }

	//获取该节点下的所有叶子节点tagId
	public List<String> getTreeTagId(String tagId){
    
    
        List returnList = new ArrayList();
        List<TagRequestVO> tag = getAllChildren(buildTreeByTag(tagId).get(0), returnList);
        List<String> tagIdList = new ArrayList<>();
        for(TagRequestVO tagChildren : tag){
    
    
            tagIdList.add(tagChildren.getTagId());
        }
        return tagIdList;
    }

Obtenha os nós folha que não possuem nós filhos em um determinado nó (sem filhos)

A construção da árvore não é muito diferente da anterior, exceto que o ID do nó (tagId) necessário para a filtragem especificada precisa ser adicionado à função de obtenção do nó raiz (getRootNodeByTag()). A estrutura da subárvore (buildChildTreeByTag()) é exatamente igual à anterior. Depois de construir a árvore, combine os nós folha abaixo dela.

getChildren() obtém todos os seus nós folha. Observe que não há filhos (nós folha) na condição de julgamento.

getTreeChildrenTagId obtém todos os seus IDs de nó folha (tagId).

	/**
     *   获取需构建的根节点,根据根节点tagId匹配
     *   @return 所有根节点List集合
     */
    public List<TagRequestVO> getRootNodeByTag(String tagId){
    
    
        QueryWrapper<Tag> wrapper = new QueryWrapper<>();
        wrapper.and(w -> w.eq("tag_id", tagId).or().eq("parent_id", tagId));
        List<Tag> nodeList = tagMapper.selectList(wrapper);
        List<TagRequestVO> rootNodeList = new ArrayList<>();
        for (Tag treeNode : nodeList){
    
    
            TagRequestVO response = new TagRequestVO();
            if (treeNode.getParentId().equals("0")) {
    
    
                response.setTagId(treeNode.getTagId());
                rootNodeList.add(response);
            }
        }
        return rootNodeList;
    }

	/**
     *  根据每一个顶级节点(根节点)进行构建树形结构
     *  @return  构建整棵树
     */
    public List<TagRequestVO> buildTreeByTag(String tagId){
    
    
        List<TagRequestVO> treeNodes = new ArrayList<>();
        for (TagRequestVO treeRootNode : getRootNodeByTag(tagId)) {
    
    
            treeRootNode = buildChildTreeByTag(treeRootNode);
            treeNodes.add(treeRootNode);
        }
        return treeNodes;
    }


	/**
     *  递归-----构建子树形结构
     *  @param  pNode 根节点(顶级节点)
     *  @return 整棵树
     */
    public TagRequestVO buildChildTreeByTag(TagRequestVO pNode){
    
    
        List<TagRequestVO> childTree = new ArrayList<>();
        List<Tag> nodeList = tagMapper.selectList(null);
        for (Tag treeNode : nodeList) {
    
    
            if (treeNode.getParentId().equals(pNode.getTagId())) {
    
    
                TagRequestVO response = new TagRequestVO();
                response.setTagId(treeNode.getTagId());
                response.setParentId(treeNode.getParentId());
                childTree.add(buildChildTreeByTag(response));
            }
        }
        pNode.setChildren(childTree);
        return pNode;
    }

	//获取该节点下 没有子节点的(没有children) 叶子节点
    private List<TagRequestVO> getChildren(TagRequestVO tagRequestVO,List returnList){
    
    
        List<TagRequestVO> childrenList = tagRequestVO.getChildren();
		// 退出递归的条件 只有一层维度结构
        if(childrenList==null || childrenList.size()<=0){
    
    
            returnList.add(tagRequestVO);
        }else{
    
    
			// 有多层维度结果
            for(TagRequestVO children : childrenList){
    
    
                getChildren(children,returnList);
            }
        }
        return returnList;
    }
    
	//获取该节点下 没有子节点的(没有children) 叶子节点的tagId
    public List<String> getTreeChildrenTagId(String tagId){
    
    
        List returnList = new ArrayList();
        List<TagRequestVO> tag = getChildren(buildTreeByTag(tagId).get(0), returnList);
        List<String> childrenTagIdList = new ArrayList<>();
        for(TagRequestVO tagChildren : tag){
    
    
            childrenTagIdList.add(tagChildren.getTagId());
        }
        return childrenTagIdList;
    }

Referência: https://blog.csdn.net/a18505947362/article/details/122458089

https://blog.csdn.net/weixin_36368404/article/details/115783785?spm=1001.2101.3001.6650.13&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-13-1157837 85-blog- 124102788.pc_relevant_multi_platform_whitelistv4&profundidade_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-13-115783785-blog-124102788.pc_relevant_multi_platform_whitelistv4&utm _relevante_index=14

Acho que você gosta

Origin blog.csdn.net/weixin_44436677/article/details/127589077
Recomendado
Clasificación