Skip to content

Latest commit

 

History

History
41 lines (31 loc) · 867 Bytes

File metadata and controls

41 lines (31 loc) · 867 Bytes

102 二叉树层序遍历

给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。

示例 1:

**输入:**root = [3,9,20,null,null,15,7] 输出:[[3],[9,20],[15,7]]

示例 2:

**输入:**root = [1] 输出:[[1]]

示例 3:

**输入:**root = [] 输出:[]

var levelOrder = function (root) {
    if (root == null) return []
    let ans = []
    let cur = [root]
    while (cur.length) {
        let nxt = []
        let vals = []
        for (const node of cur) {
            vals.push(node.val)
            if (node.left) nxt.push(node.left)
            if (node.right) nxt.push(node.right)
        }
        cur = nxt
        ans.push(vals)
    }
    return ans
};