【leetcode.填充每个节点的下一个右侧节点指针 II】

51 阅读1分钟

leetcode-117.png

这是一个比较典型的层序遍历,要求每一层的节点,都依次从左到右指向

var connect = function (root) {
    if (!root) return null
    let queue = [root]
    while (queue.length) {
        let size = queue.length
        for (let i = 0; i < size; ++i) {
            let first = queue.shift()
            if (i < size - 1) {
                first.next = queue[0]
            }
            if (first.left) queue.push(first.left)
            if (first.right) queue.push(first.right)
        }
    }
    return root
};

这是一个比较标准的层序遍历的写法,在这一题中,唯一要注意的地方就是for循环内的if判断,在这里要使倒数第二个节点指向最后一个节点,所以要限制i的范围。