递归这样理解,你将豁然开朗
递归这样理解,你将豁然开朗;
php版本
<?php
$arr = array(
array('id' => 1,'name' => 'A','parent_id' => 0),
array('id' => 2,'name' => 'B','parent_id' => 0),
array('id' => 3,'name' => 'A1','parent_id' => 1),
array('id' => 4,'name' => 'B1','parent_id' => 2),
array('id' => 5,'name' => 'A2','parent_id' => 3),
array('id' => 6,'name' => 'B2','parent_id' => 4),
);
// 递归树
function deepFunction($arr,$id){
$list = array();
foreach ($arr as $key => $value) {
if ($id == $value['parent_id']) {
$child = deepFunction($arr,$value['id']);
$value['child'] = $child;
$list[] = $value;
}
}
return $list;
}
$res = deepFunction($arr,0);
echo '<pre>';
var_dump($res);
方法1:无返回值法
@GetMapping("/index6")
public List<Integer> index6() {
Integer id = 11;
List<Category> categoryList = categoryMapper.selectList(null);
// 声明引用返回值
List<Integer> result = new ArrayList<>();
checkCateData(categoryList, id, result);
return result;
}
/**
*
* @param list 分类列表
* @param id 查询id
* @param result 搜集返回值(子分类所有id)
* @return
*/
private void checkCateData(List<Category> list, Integer id,List<Integer> result) {
for (Category ca : list
) {
if (ca.getFatherId().equals(id)){
Integer ids = ca.getId();
result.add(ids);
checkCateData(list,ids,result);
}
}
}
方法2:有返回值
/**
* 有返回值接收
* @param categoryList
* @param id
* @return
*/
private List<CategoryTreeVO> deepCategoryDataList(List<Category> categoryList, Integer id) {
List<CategoryTreeVO> result = new ArrayList<>();
for (Category cate : categoryList
) {
if (cate.getFatherId().equals(id)) {
CategoryTreeVO vo = new CategoryTreeVO();
vo.setName(cate.getName());
vo.setId(cate.getId());
vo.setType(cate.getType());
vo.setFatherId(cate.getFatherId());
List<CategoryTreeVO> childList = deepCategoryDataList(categoryList, cate.getId());
vo.setNodeCategoryList(childList);
result.add(vo);
}
}
return result;
}
方法3:
/**
* 通过子集查询父级节点
* @param list
* @param parentId
* @return
*/
private List<Integer> queryFatherItem(List<Category> list, Integer parentId) {
List<Integer> result = new ArrayList<>();
for (Category cate : list
) {
if (cate.getId().equals(parentId)) {
result.add(cate.getId());
List<Integer> integers = queryFatherItem(list, cate.getFatherId());
result.addAll(integers);
}
}
return result;
}
本作品采用《CC 协议》,转载必须注明作者和本文链接