Java递归算法实例
public static void main(String[] args) { Map<String,Object> map = new HashMap<>(); map.put("id",0); map.put("name","a"); map.put("pid",55); Map<String,Object> map1 = new HashMap<>(); map1.put("id",1); map1.put("name","aa"); map1.put("pid",0); Map<String,Object> map2 = new HashMap<>(); map2.put("id",2); map2.put("name","bb"); map2.put("pid",0); Map<String,Object> map3 = new HashMap<>(); map3.put("id",3); map3.put("name","aaa"); map3.put("pid",1); Map<String,Object> map4 = new HashMap<>(); map4.put("id",4); map4.put("name","bbb"); map4.put("pid",2); List<Map<String,Object>> list = new ArrayList<>(); list.add(map); list.add(map1); list.add(map2); list.add(map3); list.add(map4); List<Map<String, Object>> dg = dg(55, list); System.out.println(dg); } public static List<Map<String,Object>> dg(Integer id, List<Map<String,Object>> mapList){ List<Map<String,Object>> childList = new ArrayList<>(); for (Map<String,Object> map : mapList) { System.out.println(map.get("pid")); if((int)map.get("pid")== id){ childList.add(map); } } for (Map<String,Object> map : childList){ List<Map<String, Object>> childList1 = dg((Integer) map.get("id"), mapList); map.put("child",childList1); } if (childList.size()==0){ return null; } return childList; }
执行结果: