天天看點

JavaWeb - 查詢任意節點的所有子節點(包括孫子節點)

/**
 * 遞歸查詢本節點的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;
}      

繼續閱讀