JS树的遍历:广度优先遍历与深度优先遍历
先定义一颗简单的树:
let tree = [
{
label:'a',
children:[
{
label:'b',
children:[
{
label:'d'
},
{
label:'e'
}
]
},
{
label:'c',
children:[
{
label:'f'
}
]
}
]
}
]
树的广度优先遍历
广度优先遍历:从上往下对每一层依次访问,对于上面这颗树的遍历顺序为abcdef(此处算法对应到二叉树上,属于先序遍历)
实现代码:
let bf=function(tree){
let queue =tree;
for(let i=0;i<queue.length;i++){
console.log(queue[i])
if(queue[i].children) {queue=queue.concat(queue[i].children)}
}
}
输出为:
树的深度遍历
深度遍历:对每一个可能的分支路径深入到不能再深入为止,对于上面这颗树的遍历顺序为abdecf
实现:
let df=function(tree){
let nodes=[];
if(tree){
let stack=[];
stack.push(tree);
while(stack.length!=0){
let item =stack.pop();
console.log(item)
nodes.push(item);
children=item&&item.children?item.children:[];
for(let i=children.length-1;i>=0;i--){
stack.push(children[i]);
}
}
}
}
输出为: