簡(jiǎn)潔常用權(quán)限系統(tǒng)的設(shè)計(jì)與實(shí)現(xiàn)(四):不維護(hù)level,用遞歸方式構(gòu)造樹(shù)
第三篇中,我們通過(guò)維護(hù)節(jié)點(diǎn)的深度level,通過(guò)迭代所有的節(jié)點(diǎn),只需要一次,就構(gòu)造了樹(shù)。
本篇,換一種方式。
好處是:不維護(hù)節(jié)點(diǎn)的深度level,增加和修改節(jié)點(diǎn)時(shí),也不用維護(hù)。遞歸實(shí)現(xiàn),代碼比較清晰。
壞處是:節(jié)點(diǎn)較多的時(shí)候,性能可能不夠好。不能直接查詢到節(jié)點(diǎn)的深度level。當(dāng)然,如果需要level字段,在遞歸過(guò)程中,是可以計(jì)算得到的。關(guān)于在遞歸過(guò)程中,計(jì)算level,后面有介紹這種方法。
關(guān)于樹(shù)的遍歷和查找,大家都有基礎(chǔ),上面描述了一些總體思路,代碼中有注釋,基本就不用再詳細(xì)介紹了。
- //不維護(hù)節(jié)點(diǎn)的深度level,通過(guò)遞歸構(gòu)造樹(shù)
-
- public static List<Map<String, Object>> buildTree(
-
- List<Map<String, Object>> list) {
-
- //目標(biāo)樹(shù)
-
- List<Map<String, Object>> treeList = new ArrayList<Map<String, Object>>();
-
- //所有的頂級(jí)節(jié)點(diǎn)
-
- List<Map<String, Object>> rootList = TreeMenuUtil.findTopLevelNodeList(list);
-
- //所有的非頂級(jí)節(jié)點(diǎn)
-
- List<Map<String, Object>> notRootList = TreeMenuUtil.findNotRootList(list);
-
- //遍歷頂級(jí)節(jié)點(diǎn)
-
- for (Map<String, Object> root : rootList) {
-
- // 構(gòu)造子結(jié)點(diǎn)
-
- buildChildList(root, notRootList);
-
- //把根節(jié)點(diǎn)放到集合中
-
- treeList.add(root);
-
- }
-
- return treeList;
-
- }
-
- // 為一個(gè)“root節(jié)點(diǎn),這個(gè)地方的root指有孩子的節(jié)點(diǎn)”
-
- 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) {
-
- //從非頂級(jí)節(jié)點(diǎn)中,為當(dāng)前節(jié)點(diǎn)尋找子結(jié)點(diǎn)
-
- 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);
-
- //遞歸,為當(dāng)前節(jié)點(diǎn)構(gòu)造子結(jié)點(diǎn)
-
- buildChildList(notRoot, notRootList);
-
- }
-
- }
-
- }
原文首發(fā):http://fansunion.cn/article/detail/572.html
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)
點(diǎn)擊舉報(bào)。