102.层序遍历

83 阅读1分钟

思路

广度优先遍历,记录当前节点的层级并将其放入对应的数组中

代码


var levelOrder = function(root) {
    const res = []
    if(root){
        const q = [[root,0]]
        while(q.length){
            const [n,l] = q.shift()
            res[l] ? res[l].push(n.val) : res[l] = [n.val]
            if(n.left) q.push([n.left,l+1])
            if(n.right) q.push([n.right,l+1])
        }
    }
    return res;
};

入队的时候记录当前层的成员,并记录队列长度(len)

var levelOrder = function (root) {
    const res = []
    if (root) {
        const q = [root]
        while (q.length) {
            let len = q.length
            res.push([])
            while (len--) {
                const n = q.shift()
                res[res.length - 1].push(n.val)
                if (n.left) q.push(n.left)
                if (n.right) q.push(n.right)
            }
        }
    }
    return res;
};

复杂度

时间:O(n)

空间:O(n)