
什么是广度优先遍历
先访问离根节点最近的节点
深度优先遍历算法口诀
新进一个队列,把根节点入队;
把对头出队并访问;
把队头的children挨个入队;
重复第二三步知道队列为空。
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);
a b c d e f g
2694

被折叠的 条评论
为什么被折叠?



