js 实现树形数据遍历之广度优先遍历
程序员文章站
2022-05-24 08:49:27
...
接上一篇深度优先遍历
直接上方法:
// 广度优先遍历, tree 数据源, ope是回调函数,处理遍历逻辑
bfs(tree, ope) {
const walk = (tree, depth = 1) => {
const queue = [];
ope(tree, 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, item.depth);
if (node.children) {
queue.push({
nodes: node.children,
depth: item.depth + 1
});
}
});
}
};
tree.forEach(item => {
walk(item);
});
}
调用:
this.bfs(DEEPDATA, (node, depth) => {
let pre = "";
for (let i = 0; i < depth; i++) {
pre += "--";
}
console.log(pre + node.name);
});
详细可以看上一篇