一般用于dom树的或树形菜单的结构
let tree=[
{
children:[
{
children:[
{
children:[
'a',
{children:'b'}
]
},
{
children:'c'
}
]
},
{children:[{children:['d',{children:'e'}]},{children:'f'}]},
{children:[0]}
]
}
]
深度优先
//递归
function deepFirst(tree){
let res=[];
function deepIn(tree){
if(tree&&Array.isArray(tree)){
for(let i=0;i<tree.length;i++){
if(tree[i].children){
deepIn(tree[i].children)
}else{
res.push(tree[i])
}
}
}else{
res.push(tree)
}
}
deepIn(tree);
return res
}
//非递归
function deepFirst(tree){
let res=[];
let temp=tree;
while(temp.length){
let item=temp.pop();
if(item.children){
for(let i= item.children.length-1;i>=0;i--){
temp.push(item.children[i])
}
}else{
res.push(item);
}
}
return res;
}
广度优先
//非递归实现
function breadthFirst(tree){
let temp=tree;
let res=[];
while(temp.length){
if(temp[0].children){
Array.isArray(temp[0].children)?temp.push(...temp[0].children):temp.push(temp[0].children)
}else{
res.push(temp[0])
}
temp.shift();
}
return res;
}
网友评论