设计与实现简单而经常使用的权限系统(四):无需维护level,递归构建树
第三篇中。我们通过维护节点的深度level,通过迭代全部的节点,仅仅须要一次,就构造了树。
本篇。换一种方式。
优点是:不维护节点的深度level,添加和改动节点时,也不用维护。递归实现,代码比較清晰。
坏处是:节点较多的时候。性能可能不够好。不能直接查询到节点的深度level。
当然。假设须要level字段,在递归过程中,是能够计算得到的。关于在递归过程中,计算level。后面有介绍这样的方法。
关于树的遍历和查找,大家都有基础,上面描写叙述了一些整体思路,代码中有凝视,基本就不用再具体介绍了。
//不维护节点的深度level,通过递归构造树
public static List<Map<String, Object>> buildTree(
List<Map<String, Object>> list) {
//目标树
List<Map<String, Object>> treeList = new ArrayList<Map<String, Object>>();
//全部的顶级节点
List<Map<String, Object>> rootList = TreeMenuUtil.findTopLevelNodeList(list);
//全部的非顶级节点
List<Map<String, Object>> notRootList = TreeMenuUtil.findNotRootList(list);
//遍历顶级节点
for (Map<String, Object> root : rootList) {
// 构造子结点
buildChildList(root, notRootList);
//把根节点放到集合中
treeList.add(root);
}
return treeList;
}
// 为一个“root节点,这个地方的root指有孩子的节点”
private static void buildChildList(Map<String, Object> rootNode,
List<Map<String, Object>> notRootList) {
Integer acl = MapUtils.getInteger(rootNode, "acl");
for (Map<String, Object> notRoot : notRootList) {
//从非顶级节点中。为当前节点寻找子结点
boolean equals = MapUtils.getInteger(notRoot, "parent_acl").equals(acl);
if (equals) {
List<Map<String, Object>> list = (List<Map<String, Object>>) rootNode
.get("children");
if (list == null) {
list = new ArrayList<Map<String, Object>>();
rootNode.put("children", list);
}
list.add(notRoot);
//递归。为当前节点构造子结点
buildChildList(notRoot, notRootList);
}
}
}原文首发:http://fansunion.cn/article/detail/572.html版权声明:本文博主原创文章,博客,未经同意不得转载。

浙公网安备 33010602011771号