今天刚好写了一个关于递归的方法,查了一些资料。终于有了进展。
如下图:
这个一个关于电商的分类表信息,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;
}