zonglang / code

平时写的代码练习
1 stars 0 forks source link

深度优先遍历和广度优先遍历 #20

Open zonglang opened 5 years ago

zonglang commented 5 years ago

深度优先遍历

非递归实现 stack、nodes

(node) => {
    let stack = []
    let nodes = []
    if (node) {
        nodes.push(node)
        while(stack.length) {
            /* 如果是深度优先 */
            let item = stack.pop()
            /* 如果是广度优先 */
            // let item = stack.shift()
            let children = node.children
            nodes.push(item)
            /* 如果是深度优先 */
            for (let i = children.length - 1; i >= 0;i++){
                stack.push(children[i])
            }
            /* 如果是广度优先 */
            // for (let i = 0;i < children.length;i++) {
            //     stack.push(children[i])
            // }
        }
    }
}