多叉树的构建

有个需求,是一张地区表,地区表中包含多层级的地区,如:中国,河北省,邢台市,桥东区。一共有4个层级。数据库字段设计为

我要将这些数据转为有层级关系的json数据:很显然数据的结构是个树,于是就要建立树的结构:

1 public class Node{ 
2     public Map<Integer,Node> childs = new HashMap<>(); 
3     public String name; public Integer id; 
4     public Integer parentId; 
5 }

从数据库取到所有数据 attrAreas进行一个树的构建:

 1 public void local(List<ModelAttrArea> attrAreas){ //建立根节点
 2     Node root=new Node(); Map<Integer,Node> maps= new HashMap<>(); //遍历所有节点,将节点放入节点map中 
 3     for(ModelAttrArea temp:attrAreas) { 
 4         Node node = new Node(); 
 5         node.name = temp.getName(); 
 6         node.id = temp.getID(); 
 7         node.parentId = temp.getParentId(); 
 8         maps.put(temp.getID(),node); 
 9     } 
10     
11     //开始遍历已经放好的map,将没有父节点的节点放倒根目录下,把有父节点的节点,找到父节点,然后给父节点添加子节点。 
12     for (Map.Entry<Integer, Node> entry : maps.entrySet()){ 
13         Node e=entry.getValue(); 
14         Integer parentId = e.parentId; 
15         if(parentId==null){ 
16             root.childs.put(e.id, e); 
17         }else{ 
18             Node pnode = maps.get(parentId); 
19             pnode.childs.put(e.id,e); 
20             } 
21         } 
22     }
23 }

参考地址:http://www.imooc.com/article/6909?block_id=tuijian_wz

原文地址:https://www.cnblogs.com/lezhifang/p/7128299.html