广度优先遍历

    科技2022-08-08  101

    什么是广度优先遍历

    先访问离根节点最近的节点

    深度优先遍历算法口诀

    新进一个队列,把根节点入队; 把对头出队并访问; 把队头的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
    Processed: 0.010, SQL: 8