树的广度优先遍历

相关标签: # php
广度优先遍历算法口诀:
1. 新建一个队列,把根节点入队。
2. 把队头出队并访问。
3. 把队头的children挨个入队。
4. 重复第二、三步,直到队列为空。
const tree = {
val: 'a',
children: [
{
val: 'b',
children: [
{
val: 'd',
children: [],
},
{
val: 'e',
children: [],
}
],
},
{
val: 'c',
children: [
{
val: 'f',
children: [],
},
{
val: 'g',
children: [],
}
],
}
],
};
const bfs = (root) => {
const q = [root];
while (q.length > 0) {
const n = q.shift();
console.log(n.val);
n.children.forEach(child => {
q.push(child);
});
}
};
bfs(tree);
文章来源: https://blog.51cto.com/u_15765713/5673416
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报