深度优先与广度优先

深度优先:先将自己所有子元素遍历完,再回来遍历下一个邻近节点。递归就是深度优先遍历。
广度优先:先将自己与邻近节点这一层遍历完,再遍历自已与邻近节点下的第一层子节点,直至遍历结束。
a
b
c
// 深度优先
let parent = document.querySelector('#parent');
let deepTraversal1 = (node, nodeList = []) => {
    if (node !== null) {
        nodeList.push(node)
        let children = node.children
        for (let i = 0; i < children.length; i++) {
            deepTraversal1(children[i], nodeList)
        }
    }
    return nodeList
}
console.log(deepTraversal1(parent));
image.png
// 广度优先
let widthTraversal2 = (node) => {
    let nodes = [] // 存储元素集合
    let stack = [] // 遍历元素集合 按顺序先进先出一层一层遍历
    if (node) {
        stack.push(node)
         while (stack.length) {
             let item = stack.shift()
             let children = item.children
             nodes.push(item)
             // 队列,先进先出
             // nodes = [] stack = [parent]
             // nodes = [parent] stack = [child1,child2,child3]
             // nodes = [parent, child1] stack = [child2,child3,child1-1,child1-2]
             // nodes = [parent,child1,child2]
             for (let i = 0; i < children.length; i++) {
                 stack.push(children[i])
             }
         }
     }
    return nodes
}
console.log(widthTraversal2(parent));
image.png

你可能感兴趣的:(深度优先与广度优先)