java递归实例(一)---递归构造Tree结构

/**
 * 递归算法测试
 * @author ASUS
 *
 */
public class RecursionTest {
	
	public String getCategrotyRel(Integer parentId,Integer idMerchant)
		throws Exception{
//		parentId = 0;//
		String retStr = "[{\"catName\":\"手机\",\"id\":1,\"parentId\":0}"
				+ "{\"catName\":\"苹果\",\"id\":2,\"parentId\":1},"
				+ "{\"catName\":\"小米\",\"id\":3,\"parentId\":1},"
				+ "{\"catName\":\"电脑\",\"id\":4,\"parentId\":0}]";
		List<Map> opeCateInfoList = JsonUtil.jsonToObjectList(retStr, Map.class);
		List<Map<String,Object>> retList = this.setMchtRelTree(parentId,idMerchant,opeCateInfoList);
		return JsonUtil.objectToString(retList);
	}

	//递归构造树结构数据
	private List<Map<String, Object>> setMchtRelTree(Integer parentId,
			Integer idMerchant, List<Map> opeCateInfoList) throws Exception {
		
		List<Map> interRes = opeCateInfoList;
		List<Map<String,Object>> retList = new ArrayList<Map<String,Object>>();
		//根据父节点ID 获取所有 关系
		List<MchtOpeCatRel> rsList = mchtOpeCatRelMapper.getOpeCatRel(idMerchant,parentId);
		if(rsList != null && rsList.size() > 0){
			for(MchtOpeCatRel item : rsList){
				Map<String,Object> data = new HashMap<String,Object>();
				for(Map<String,Object> map : interRes){
					if(((Integer)map.get("id")).intValue() == item.getIdOpeCate().intValue()){
						data.put("name", (String)map.get("catName"));
					}
				}
				data.put("idOpeCate", item.getIdOpeCate());
				data.put("parentId", item.getParentId());
				//以当前idOpeCate为父节点,递归查询 所有 关系
				List<Map<String,Object>> childList = setMchtRelTree(item.getIdOpeCate(),
						idMerchant,interRes);
				if(childList != null && childList.size() > 0){
					data.put("children", childList);
				}
				retList.add(data);
 			}
		}
		
		return retList;
	}
}

由于关系表mcht_opecat_rel中存的是ID之间的关系,ID对应的name会随时改变,因此需要实时调用接口获取(接口部分忽略,如上述代码中写死的retStr)

第一次调用getCategrotyRel()时,parentId传人的是0,即先构造一级节点,然后逐级构造。

这样运行结果如下:

[{idOpeCate=1, name=手机, parentId=0, children=[{idOpeCate=2, name=苹果, parentId=1}, {idOpeCate=3, name=小米, parentId=1}]}, 

{idOpeCate=4, name=电脑, parentId=0}]

    原文作者:递归与分治算法
    原文地址: https://blog.csdn.net/yansong_8686/article/details/50361479
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞