js中树结构的深度优先遍历(DFS)和广度优先遍历(BFS)
作者:互联网
深度优先:先遍历完一个节点的所有子孙节点,自上而下。
广度优先:先遍历同层节点,逐层遍历。
const list = [ { name: "河南", children: [ { name: "信阳", children: [ { name: "商城" }, { name: "固始" }, ], }, { name: "南阳", children: [ { name: "镇平" }, { name: "新野" } ], }, ], }, { name: "安徽", children: [ { name: "六安", children: [ { name: "金寨" }, { name: "霍邱" }, ], }, { name: "合肥", children: [ { name: "肥东" }, { name: "肥西" }, ], }, ], }, ];
深度优先(递归实现)
var dfs = (function() { var arr = [] return function(data) { data.forEach(item => { arr.push(item.name) if (item.children && item.children.length > 0) { dfs(item.children) } }); return arr } })() var newData = dfs(list) // ['河南', '信阳', '商城', '固始', '南阳', '镇平', '新野', '安徽', '六安', '金寨', '霍邱', '合肥', '肥东', '肥西']
广度优先(队列形式)
var bfs = (function() { var arr = [] return function (data) { for(var i = 0; i < data.length; i++) { arr.push(data[i].name) if (data[i].children && data[i].children.length > 0) { data.push(...data[i].children) // 入队 } } return arr } })() var newData2 = bfs(list) // ['河南', '安徽', '信阳', '南阳', '六安', '合肥', '商城', '固始', '镇平', '新野', '金寨', '霍邱', '肥东', '肥西']
标签:优先,遍历,name,树结构,arr,item,var,data,children 来源: https://www.cnblogs.com/zhaoyd2013/p/16287846.html