• 简洁常用权限系统的设计与实现(四):不维护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

  • 相关阅读:
    web安全之ssrf
    web安全之sql注入布尔注入
    web安全之sql注入报错型注入
    web安全之sqlload_file()和into outfile()
    浅谈 FHQ-Treap
    (菜鸟都能看懂的)网络最大流最小割,Ford-Fulkerson及Dinic详解
    浅谈最小生成树
    浅谈强连通分量(Tarjan)
    DP-DAY3游记
    关于01背包问题
  • 原文地址:https://www.cnblogs.com/qitian1/p/6463017.html
Copyright © 2020-2023  润新知