小白:关于java递归方法的总结

今天刚好写了一个关于递归的方法,查了一些资料。终于有了进展。

如下图:

这个一个关于电商的分类表信息,id(“catrgory_id")

思路:

1.如果我的根id是100001,现在我想得到关于儿子节点的所有100001对应的id。

2.先去查找根id1000001是否存在,如果存在的话,我会把对象放到set<>集合中(提前实现这个类的equals和hashcode方法的重现,为了避免set装一样的对象进去)

3.我会用id.100001.当做parend_id,去接着查找所有的子对象集合。

4.最重要的来了,最重要的来了,最重要的来了。通过上面的集合我可以获取到子节点对应的id。我会在这里调用踏自己,参数里面会放入set的引用和子节点对应的id遍历。 

-----------待续。下来给看管直接上代码。

 public ServerResponse<List<Integer>> selectGetDeepCategory(Integer catrgoryId){
        //创建一个list
        Set<Category> categorySet = Sets.newHashSet();
        List<Integer> categoriesList = Lists.newArrayList();
        //引用已经返回了
        if (catrgoryId !=null) {
            findChildCategory(categorySet, catrgoryId);
            //遍历set的时候,把categoryId装到集合在返回去
            for (Category categoryItem : categorySet) {
                 categoriesList.add(categoryItem.getId());
            }
        }
        return ServerResponse.createBySuccessData(categoriesList);
    }
    //递归算法
    private Set<Category> findChildCategory(Set<Category> categorySet,Integer categoryId){
            //如果父节点有值往下走
        Category category = this.categoryMapper.selectByPrimaryKey(categoryId);
        //如果集合不等于空,先添加到set
        if (category != null){
            categorySet.add(category);
        }
        //递归的时候要有结束点,拿parentId去查所有的子节点
        List<Category> childparentIdList = this.categoryMapper.getChildparentIdList(categoryId);
        if (!CollectionUtils.isEmpty(childparentIdList)){
            //遍历一下
            for (Category list:childparentIdList) {
                findChildCategory(categorySet,list.getId());
            }
        }
        //把引用返回去
        return categorySet;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值