JS广度优先遍历
自己用JS实现了 广度优先遍历
第一种用了数组的高阶函数,看起来有些复杂。然后思索着从可读性上优化了一下,孰优孰劣以后分析。
var list = [{
id: "ab",
children: [{
id: "ab1",
children: [{
id: "ab11",
children: []
}]
},{
id: "ab2",
children: []
}, {
id: "cd",
children: [{
id: "aa",
children: []
}, {
id: "ef",
children: []
}]
}]
},{
id:'cc',
children:[]
},{
id:'dd',
children:[]
}]
// path[] 1.将list 数组合并到path, 2.从头部开始删除,看是否有子节点,有就合并到path[] 3.重复2,直到path 为空
function breadthFirstSearch(list)
{
let tree=[];
let path = list.reduce((acc,cur)=>acc=[].concat(acc,cur));
while(path.length>0){
let node = path.shift();
tree.push(node.id);
let target = node.children;
// console.log(target.length,node.id,target)
if(target.length !== 0){
path=[].concat(path, ...target.length==1?target:target.reduce((acc,cur)=>acc=[].concat(acc,cur)));
}
}
return tree;
}
console.log(breadthFirstSearch(list))
// [
// 'ab', 'cc',
// 'dd', 'ab1',
// 'ab2', 'cd',
// 'ab11', 'aa',
// 'ef'
// ]
// 非递归: 1.创建新的数组nodeList, 并赋值list 2.从头遍历nodeList的子节点,并合并到nodeList
function breadthFirstSearch1(list){
let index=0;
let tree=[];
let nodeList = [...list];
while(index<nodeList.length){
const node=nodeList[index++];
tree.push(node.id);
if(node.children){
for(let k in node.children){
nodeList.push(node.children[k]);
}
}
}
return tree;
// return nodeList;
}
console.log(breadthFirstSearch1(list))