1. 程式人生 > >java遞迴實現商品分類例子

java遞迴實現商品分類例子

在對商品進行分類時,類別表會出現父節點

遞迴查詢本節點的id及孩子節點的id

/** * 遞迴查詢本節點的id及孩子節點的id * @param categoryId* @return*/public ServerResponse<List<Integer>> selectCategoryAndChildrenById(Integer categoryId){    Set<Category> categorySet = Sets.newHashSet();    findChildCategory(categorySet,categoryId);    List<Integer> categoryIdList = Lists.

newArrayList();     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;}