const data = {
name: 'all',
children: [
{
name: '图片',
children: [
{
name: 'image1.jpg'
},
{
name: '风景',
children: [
{
name: 'guilin.jpg'
},
{
name: 'hainan.jpg'
}
]
},
{
name: 'image2.jpg'
}
],
},
{
name: '视频',
children: [
{
name: 'video1.mp4'
},
{
name: 'video2.mp4'
}
]
},
{
name: '文档',
children: [
{
name: 'document1.doc'
},
{
name: '小说',
children: [
{
name: 'novel.txt'
},
{
name: 'novel2.txt'
}
]
},
{
name: 'document2.doc'
}
]
}
]
}
const bfs = (tree, ope) => {
const walk = (tree, depth = 1) => {
const queue = []
ope(tree.name, depth)
if(tree.children){
queue.push({
nodes: tree.children,
depth: depth + 1
})
}
while(queue.length) {
const item = queue.pop()
item.nodes && item.nodes.forEach(node => {
ope(node.name, item.depth)
if(node.children) {
queue.push({
nodes: node.children,
depth: item.depth + 1
})
}
})
}
}
walk(tree)
}
bfs(data,(name, depth) => {
let pre = '';
for(let i =0; i < depth; i++) {
pre += '--'
}
document.write(pre + name + '<br>')
})
console