一、模块分类
1、获取节点
2、增加节点
3、修改名字
4、获取分类ID
5、递归子节点
二、目标:
1、如何设计及封装无限层级的树状数据结构
使用id和parent_id就能设计出无限层级的树状结构
2、递归算法的设计思想(重点)
/**
* 递归查询本节点id及孩子节点的id
* @param categoryId
* @return
*/
public ServerResponse selectCategoryAndChildrenById(Integer categoryId){
Set<Category> categorySet= Sets.newHashSet();//newHashSet 创建一个新的Set
findChildCategory(categorySet,categoryId);
List<Integer> categoryIdList= Lists.newArrayList();//newArrayList 创建一个新的List
if(categoryId!=null){
for (Category categoryItem:categorySet){
categoryIdList.add(categoryItem.getId());
}
}
return ServerResponse.createBySuccess(categoryIdList);
}
//书写递归算法,自己调自己
private Set<Category> findChildCategory(Set<Category> categorySet,Integer categoryId){
Category category=categoryMapper.selectByPrimaryKey(categoryId);
if(category!=null){
categorySet.add(category);
}
//查询字节点,递归算法一定要有一个退出的条件
List<Category> categoryList=categoryMapper.selectCategoryChildrenByParentId(categoryId);
for(Category categoryItem:categoryList){
findChildCategory(categorySet,categoryItem.getId());
}
return categorySet;
}
注:用了Set就需要重写Category类的hashcode和equal。
3、如何处理复杂对象排重
4、重写hashcode和equal的注意事项