ziv-zjc/blog

树操作

ziv-zjc opened this issue · 0 comments

树操作

遍历

/**
 * 广度遍历优先,获取叶子节点
 * @param {*} obj 
 * 
 * let obj = {a:1, b:"sdf", c:{d: 123, e: "vv"}, f:{g:{h:{i:"afs"}, j:4545}, k: 123}, l: 23 }
 */

function bfsTraverse(obj) {
    let leafList = []
    let stack = [...Object.values(obj)]

    while (stack.length) {
        let item = stack.shift()
        if (item && typeof item != 'object') {
            leafList.push(item)
        } else {
            Object.values(item).forEach((childValue) => {
                stack.push(childValue)
            })
        }
    }
    return leafList
}