递归与栈

递归即方法调用自身。递归可以用栈加循环实现转换。
递归增强了代码的可读性,但是牺牲了内存消耗。

递归写法:

/**
* 将树状结构组织机构数据放入准备数据中
* @param dto当前遍历的组织机构
* @param allOrganizationDtos 所有组织机构串
* @param preparedData 组织机构准备数据串
*/
private void putDataTreeIntoPrepared(OrganizationDto dto, 
List<OrganizationDto> allOrganizationDtos, List<OrganizationDto> preparedData) {
    //查询出当前结点的父亲结点
    List<OrganizationDto> parents = allOrganizationDtos.stream ()
            .filter (organizationDto -> dto.getParentId ().equals (organizationDto.getId ()))
            .collect (Collectors.toList ());
    if(!preparedData.contains (dto)){
        preparedData.add(dto);//放入准备数据
    }
    for(OrganizationDto p:parents){
        if(p.getParentId ()!=null || !"0".equals (p.getParentId ())){
        //如果有父节点,则继续递归查询
            putDataTreeIntoPrepared(p, allOrganizationDtos, preparedData);
        }
    }
}

栈写法:
替换思路即是,每一次调用递归,都压入栈。

private void putDataTreeIntoPrepared(OrganizationDto dto, 
List<OrganizationDto> allOrganizationDtos, List<OrganizationDto> preparedData) {
        //查询出当前结点的父亲结点
        List<OrganizationDto> parents = allOrganizationDtos.stream ()
                .filter (organizationDto -> dto.getParentId ().equals (organizationDto.getId ()))
                .collect (Collectors.toList ());
        if(!preparedData.contains (dto)){
            preparedData.add(dto);
        }
        Stack<OrganizationDto> stack = new Stack<OrganizationDto>();
        for(OrganizationDto p:parents){
            stack.push (p);
        }
        while (!stack.empty ()){
            OrganizationDto o = stack.pop ();
            //查询出当前结点的父亲结点
            List<OrganizationDto> subParents = allOrganizationDtos.stream ()
                    .filter (organizationDto -> o.getParentId ().equals (organizationDto.getId ()))
                    .collect (Collectors.toList ());
            if(!preparedData.contains (o)){
                preparedData.add(o);
            }
            for(OrganizationDto p:subParents){
                stack.push (p);
            }
        }
    }

优化代码结构后:

private void putDataTreeIntoPrepared(OrganizationDto dto, 
List<OrganizationDto> allOrganizationDtos, List<OrganizationDto> preparedData) {

        Stack<OrganizationDto> stack = new Stack<>();
        stack.push (dto);
        while (!stack.empty ()){
            OrganizationDto o = stack.pop ();
            //查询出当前结点的父亲结点
            List<OrganizationDto> subParents = allOrganizationDtos.stream ()
                    .filter (organizationDto -> o.getParentId ().equals (organizationDto.getId ()))
                    .collect (Collectors.toList ());
            if(!preparedData.contains (o)){
                preparedData.add(o);
            }
            for(OrganizationDto p:subParents){
                stack.push (p);
            }
        }
    }

你可能感兴趣的:(JAVA)