DB思想:
数据表中存储本级节点信息和上级节点ID
tree 字段包括:
id,本级节点ID PK
parentId,上级节点ID,若无上级节点,则默认为-1
content ,本级节点内容
查出列表结构,并且按照id字段升序排列
SELECT * FROM tree ORDER BY id ASC;
代码思想:
1:创建root节点,节点ID 为-1,作为最上级节点
2:创建<id,Node>的Map ,存储root节点。
3:遍历列表结构,创建该节点的数据结构对象,并且放入到Map中,
4:查询该节点的父级节点,若父节点不存在,则该树形结构有问题,若存在,加入到该父节点的孩子列表中
这样做的好处是,使用空间换取时间,降低时间复杂度,只需要进行一次遍历,即可查询出结果。
将列表转换为树形结构的的代码如下:
public class ListTree {
public static Node sort(List<Map<String, Object>> list) throws Exception {
Map<Integer, Node> nodeMap = new HashMap<Integer, ListTree.Node>();
ListTree tree = new ListTree();
// 创建root节点
ListTree.Node root = tree.new Node();
root.setId(-1);
nodeMap.put(root.getId(), root);
for (Map<String, Object> node : list) {
Node n = tree.new Node();
int id = Integer.parseInt(node.get("id").toString());
int parentID = Integer.parseInt(node.get("parentID").toString());
String content = node.get("content").toString();
n.setId(id);
n.setParentID(parentID);
n.setContent(content);
nodeMap.put(n.getId(), n);
if (nodeMap.containsKey(parentID)) {
Node parentNode = nodeMap.get(parentID);
List<Node> childs = parentNode.getChilds();
if (childs == null) {
parentNode.setChilds(new ArrayList<Node>());
childs = parentNode.getChilds();
}
childs.add(n);
} else {
throw new Exception("数据不正确");
}
}
return root;
}
class Node {
int id;
int parentID;
String content;
List<Node> childs;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getParentID() {
return parentID;
}
public void setParentID(int parentID) {
this.parentID = parentID;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public List<Node> getChilds() {
return childs;
}
public void setChilds(List<Node> childs) {
this.childs = childs;
}
}
}
测试代码如下:
public static void main(String[] args) throws Exception {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Map<String, Object> node1 = new HashMap<String, Object>();
node1.put("id", "1");
node1.put("parentID", "-1");
node1.put("content", "权限");
list.add(node1);
Map<String, Object> node2 = new HashMap<String, Object>();
node2.put("id", "2");
node2.put("parentID", "-1");
node2.put("content", "用户");
list.add(node2);
Map<String, Object> node11 = new HashMap<String, Object>();
node11.put("id", "11");
node11.put("parentID", "1");
node11.put("content", "管理员权限");
list.add(node11);
Map<String, Object> node111 = new HashMap<String, Object>();
node111.put("id", "111");
node111.put("parentID", "11");
node111.put("content", "管理员权限-张三");
list.add(node111);
Node n = sort(list);
}