html遍历无限级树,无限级树构造并遍历输出指定条件叶子

目录

场景介绍

数据

实现

构造无限级

广度优先遍历

深度优先遍历

完整代码

场景介绍

最近接到一个需求,需要根据平级结构构造无限级树型结构,界面类似下边这样的结构

1270fe8c5d858b4e65ad087534df67bd.png

然后,还需要把所有的橙色标记的叶子节点从垂直方向筛选出来,最终效果就是得到一个这样顺序的一级数组

KKK

QQQ

JJJ

HHH

GGG

LLL

需要根据AAA这个节点和他所有子节点的数据,构造出一个无限级树型结构,如下

43080206bbab2928a67ac780aea6f424.png

数据

顶级AAA数据

{"id":348019,"name":"AAA","is_leaf":2,"parent_id":347234,"type":0,"order":["348020"]}

AAA所有的孩子节点

[{"id":348020,"name":"BBB","is_leaf":2,"parent_id":348019,"type":0,"order":["348037","348033","348021","348023","348034"]},{"id":348021,"name":"CCC","is_leaf":2,"parent_id":348020,"type":0,"order":["348022","348035"]},{"id":348022,"name":"DDD","is_leaf":2,"parent_id":348021,"type":0,"order":["348024","348032","348030"]},{"id":348024,"name":"EEE","is_leaf":2,"parent_id":348022,"type":0,"order":["348025","348036"]},{"id":348025,"name":"FFF","is_leaf":2,"parent_id":348024,"type":0,"order":["348031"]},{"id":348030,"name":"HHH","is_leaf":1,"parent_id":348022,"type":11,"order":[]},{"id":348023,"name":"GGG","is_leaf":1,"parent_id":348020,"type":11,"order":[]},{"id":348031,"name":"QQQ","is_leaf":1,"parent_id":348025,"type":11,"order":[]},{"id":348032,"name":"JJJ","is_leaf":1,"parent_id":348022,"type":11,"order":[]},{"id":348035,"name":"MMMu65e0u53f6u5b50","is_leaf":2,"parent_id":348021,"type":0,"order":[]},{"id":348036,"name":"NNNu65e0u53f6u5b50","is_leaf":2,"parent_id":348024,"type":0,"order":[]},{"id":348033,"name":"KKK","is_leaf":1,"parent_id":348020,"type":11,"order":[]},{"id":348037,"name":"OOO","is_leaf":2,"parent_id":348020,"type":0,"order":[]},{"id":348034,"name":"LLL","is_leaf":1,"parent_id":348020,"type":11,"order":[]}]

节点数据库结构都一样,核心是有一个parent_id,每个节点会保存直属叶子的排序order

实现

其实这里考察的是递归思想构造无限级,还有如果遍历一棵树,话不多说,上套路

构造无限级

private function getTree($list, $node)

{

$tree = [];

foreach ($list as $k => $v) {

if ($v['parent_id'] == $node['id']) {

$v['children'] = $this->getTree($list, $v);

$tree[] = $v;

}

}

if (empty($node['order'])) {

return [];

}

//注意:为了保证所有的叶子节点是根据已有的order排序,这里我们重新摆放一下

$treeMap = [];

foreach ($tree as $v) {

$treeMap[$v['id']] = $v;//建立id和数据的map

}

//根据order重新排序

$orderTree = [];

foreach ($node['order'] as $id) {//根据order的顺序重新摆放

$orderTree[] = $treeMap[$id];

}

return $orderTree;

}

我们来使用一下,使用如下

最终输出的json如下

3b35147f3cdc807a18e0027a498416c7.png

3446fb601d9cc6bb178763f67f0775b7.png

可以看到,已经构造出了一个无限级的树,并且和我们的界面是一模一样的层级和顺序

拉下来现在我们要遍历这棵树,为了获取到所有is_leaft=1的节点,我们先用广度优先遍历来试一下,因为这个对于找节点来说性能比较高

广度优先遍历

代码如下

private function bfsFindLeafs($node)

{

$result = [];//满足条件的组合

$q = [];

$q[] = $node;

while (count($q) > 0) {

$size = count($q);

for ($i = 0; $i < $size; $i++) {

$current = array_pop($q);

//判断节点如果是满足条件,加入路径

if ($current['is_leaf'] == 1) {

$result[] = $current;

}

//把所有的子节点加入队列

foreach ($current['children'] as $v) {

$q[] = $v;

}

}

}

return $result;

}

我们来使用一下

$getAllLeafs = $this->bfsFindLeafs($topNode);

echo json_encode($getAllLeafs);

运行后输出

[

{

"id": 348034,

"name": "LLL",

"is_leaf": 1,

"parent_id": 348020,

"type": 11,

"order": [],

"children": []

},

{

"id": 348023,

"name": "GGG",

"is_leaf": 1,

"parent_id": 348020,

"type": 11,

"order": [],

"children": []

},

{

"id": 348030,

"name": "HHH",

"is_leaf": 1,

"parent_id": 348022,

"type": 11,

"order": [],

"children": []

},

{

"id": 348032,

"name": "JJJ",

"is_leaf": 1,

"parent_id": 348022,

"type": 11,

"order": [],

"children": []

},

{

"id": 348031,

"name": "QQQ",

"is_leaf": 1,

"parent_id": 348025,

"type": 11,

"order": [],

"children": []

},

{

"id": 348033,

"name": "KKK",

"is_leaf": 1,

"parent_id": 348020,

"type": 11,

"order": [],

"children": []

}

]

好,我们已经可以获取到所有is_leaf为1的节点了,但是这里有一个问题,不是从上到下输出的

LLL

GGG

HHH

JJJ

QQQ

KKK

这时候,我们就需要一个深度优先遍历来实现了

深度优先遍历

深度优先遍历其实就是回滚算法的一种,为了从上到下输出,需要先序遍历

private function dfsFindLeafs($node)

{

$trackList = [];

foreach ($node['children'] as $v) {

if ($v['is_leaf'] == 1) {

$trackList[] = $v;

}

if (empty($v['children'])) {

continue;

}

$trackList = array_merge($trackList,$this->dfsFindLeafs($v));

}

return $trackList;

}

我们再来运行一下

$getAllLeafs = $this->dfsFindLeafs($topNode);

echo json_encode($getAllLeafs);

输出

[

{

"id": 348033,

"name": "KKK",

"is_leaf": 1,

"parent_id": 348020,

"type": 11,

"order": [],

"children": []

},

{

"id": 348031,

"name": "QQQ",

"is_leaf": 1,

"parent_id": 348025,

"type": 11,

"order": [],

"children": []

},

{

"id": 348032,

"name": "JJJ",

"is_leaf": 1,

"parent_id": 348022,

"type": 11,

"order": [],

"children": []

},

{

"id": 348030,

"name": "HHH",

"is_leaf": 1,

"parent_id": 348022,

"type": 11,

"order": [],

"children": []

},

{

"id": 348023,

"name": "GGG",

"is_leaf": 1,

"parent_id": 348020,

"type": 11,

"order": [],

"children": []

},

{

"id": 348034,

"name": "LLL",

"is_leaf": 1,

"parent_id": 348020,

"type": 11,

"order": [],

"children": []

}

]

顺序为

KKK

QQQ

JJJ

HHH

GGG

LLL

这次顺序终于对了,oh yeah~,和我们之前的界面垂直顺序一致

bc6ac9a802368e6392e9f9190c5c6fd9.png

完整代码

下面给出完整代码

/**

* Class Test

* @author chenqionghe

*/

class Test

{

public function run()

{

$topNodeJson = '{"id":348019,"name":"AAA","is_leaf":2,"parent_id":347234,"type":0,"order":["348020"]}';

$childrenJson = '[{"id":348020,"name":"BBB","is_leaf":2,"parent_id":348019,"type":0,"order":["348037","348033","348021","348023","348034"]},{"id":348021,"name":"CCC","is_leaf":2,"parent_id":348020,"type":0,"order":["348022","348035"]},{"id":348022,"name":"DDD","is_leaf":2,"parent_id":348021,"type":0,"order":["348024","348032","348030"]},{"id":348024,"name":"EEE","is_leaf":2,"parent_id":348022,"type":0,"order":["348025","348036"]},{"id":348025,"name":"FFF","is_leaf":2,"parent_id":348024,"type":0,"order":["348031"]},{"id":348030,"name":"HHH","is_leaf":1,"parent_id":348022,"type":11,"order":[]},{"id":348023,"name":"GGG","is_leaf":1,"parent_id":348020,"type":11,"order":[]},{"id":348031,"name":"QQQ","is_leaf":1,"parent_id":348025,"type":11,"order":[]},{"id":348032,"name":"JJJ","is_leaf":1,"parent_id":348022,"type":11,"order":[]},{"id":348035,"name":"MMMu65e0u53f6u5b50","is_leaf":2,"parent_id":348021,"type":0,"order":[]},{"id":348036,"name":"NNNu65e0u53f6u5b50","is_leaf":2,"parent_id":348024,"type":0,"order":[]},{"id":348033,"name":"KKK","is_leaf":1,"parent_id":348020,"type":11,"order":[]},{"id":348037,"name":"OOO","is_leaf":2,"parent_id":348020,"type":0,"order":[]},{"id":348034,"name":"LLL","is_leaf":1,"parent_id":348020,"type":11,"order":[]}]';

$topNode = json_decode($topNodeJson, true);

$childrenList = json_decode($childrenJson, true);

$topNode['children'] = $this->getTree($childrenList, $topNode);

$getAllLeafs = $this->dfsFindLeafs($topNode);

echo json_encode($getAllLeafs);

}

/**

* 递归构造无限级树

*

* @param $list

* @param $node

* @return array

*/

private function getTree($list, $node)

{

$tree = [];

foreach ($list as $k => $v) {

if ($v['parent_id'] == $node['id']) {

$v['children'] = $this->getTree($list, $v);

$tree[] = $v;

}

}

if (empty($node['order'])) {

return [];

}

//注意:为了保证所有的叶子节点是根据已有的order排序,这里我们重新摆放一下

$treeMap = [];

foreach ($tree as $v) {

$treeMap[$v['id']] = $v;//建立id和数据的map

}

//根据order重新排序

$orderTree = [];

foreach ($node['order'] as $id) {//根据order的顺序重新摆放

$orderTree[] = $treeMap[$id];

}

return $orderTree;

}

/**

* 广度优先遍历获取所有叶子

* @param $node

* @return array

*/

private function bfsFindLeafs($node)

{

$result = [];//满足条件的组合

$q = [];

$q[] = $node;

while (count($q) > 0) {

$size = count($q);

for ($i = 0; $i < $size; $i++) {

$current = array_pop($q);

//判断节点如果是满足条件,加入路径

if ($current['is_leaf'] == 1) {

$result[] = $current;

}

//把所有的子节点加入队列

foreach ($current['children'] as $v) {

$q[] = $v;

}

}

}

return $result;

}

/**

* 获取所有的叶子路径(深度度优先遍历)

*/

private function dfsFindLeafs($node)

{

$trackList = [];

foreach ($node['children'] as $v) {

if ($v['is_leaf'] == 1) {

$trackList[] = $v;

}

if (empty($v['children'])) {

continue;

}

$trackList = array_merge($trackList, $this->dfsFindLeafs($v));

}

return $trackList;

}

}

(new Test())->run();

ok,到这里我们就已经学会如何构造无限级树型结构,并学会用深度优先遍历垂直输出指定条件节点,还知道了怎么用广度优先遍历,giao~

程序员灯塔

转载请注明原文链接:无限级树构造并遍历输出指定条件叶子

无限级树(Java递归) 2007-02-08 10:26 这几天,用java写了一个无限极的树,递归写的,可能代码不够简洁,性能不够好,不过也算是练习,这几天再不断改进。前面几个小图标的判断,搞死我了。 package com.nickol.servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.nickol.utility.DB; public class category extends HttpServlet { /** * The doGet method of the servlet. * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out .println(""); out.println(""); out.println(" Category" + "" + "body{font-size:12px;}" + "" + "" + ""); out.println(" "); out.println(showCategory(0,0,new ArrayList(),"0")); out.println(" "); out.println(""); out.flush(); out.close(); } public String showCategory(int i,int n,ArrayList frontIcon,String countCurrent){ int countChild = 0; n++; String webContent = new String(); ArrayList temp = new ArrayList(); try{ Connection conn = DB.GetConn(); PreparedStatement ps = DB.GetPs("select * from category where pid = ?", conn); ps.setInt(1, i); ResultSet rs = DB.GetRs(ps); if(n==1){ if(rs.next()){ webContent += "";//插入结尾的减号 temp.add(new Integer(0)); } webContent += " ";//插入站点图标 webContent += rs.getString("cname"); webContent += "\n"; webContent += showCategory(Integer.parseInt(rs.getString("cid")),n,temp,"0"); } if(n==2){ webContent += "\n"; }else{ webContent += "\n"; } while(rs.next()){ for(int k=0;k<frontIcon.size();k++){ int iconStatic = ((Integer)frontIcon.get(k)).intValue(); if(iconStatic == 0){ webContent += "";//插入空白 }else if(iconStatic == 1){ webContent += "";//插入竖线 } } if(rs.isLast()){ if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += "";//插入结尾的减号 temp = (ArrayList)frontIcon.clone(); temp.add(new Integer(0)); }else{ webContent += "";//插入结尾的直角 } }else{ if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += "";//插入未结尾的减号 temp = (ArrayList)frontIcon.clone(); temp.add(new Integer(1)); }else{ webContent += "";//插入三叉线 } } if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += " ";//插入文件夹图标 }else{ webContent += " ";//插入文件图标 } webContent += rs.getString("cname"); webContent += "\n"; webContent += showCategory(Integer.parseInt(rs.getString("cid")),n,temp,countCurrent+countChild); countChild++; } webContent += "\n"; DB.CloseRs(rs); DB.ClosePs(ps); DB.CloseConn(conn); }catch(Exception e){ e.printStackTrace(); } return webContent; } public boolean checkChild(int i){ boolean child = false; try{ Connection conn = DB.GetConn(); PreparedStatement ps = DB.GetPs("select * from category where pid = ?", conn); ps.setInt(1, i); ResultSet rs = DB.GetRs(ps); if(rs.next()){ child = true; } DB.CloseRs(rs); DB.ClosePs(ps); DB.CloseConn(conn); }catch(Exception e){ e.printStackTrace(); } return child; } } --------------------------------------------------------------------- tree.js文件 function changeState(countCurrent,countChild){ var object = document.getElementById("level" + countCurrent + countChild); if(object.style.display=='none'){ object.style.display='block'; }else{ object.style.display='none'; } var cursor = document.getElementById("cursor" + countCurrent + countChild); if(cursor.src.indexOf("images/tree_minus.gif")>=0) {cursor.src="images/tree_plus.gif";} else if(cursor.src.indexOf("images/tree_minusbottom.gif")>=0) {cursor.src="images/tree_plusbottom.gif";} else if(cursor.src.indexOf("images/tree_plus.gif")>=0) {cursor.src="images/tree_minus.gif";} else {cursor.src="images/tree_minusbottom.gif";} var folder = document.getElementById("folder" + countCurrent + countChild); if(folder.src.indexOf("images/icon_folder_channel_normal.gif")>=0){ folder.src = "images/icon_folder_channel_open.gif"; }else{ folder.src = "images/icon_folder_channel_normal.gif"; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值