Skip to content

102. 二叉树的层序遍历 #41

@webVueBlog

Description

@webVueBlog

102. 二叉树的层序遍历

Description

Difficulty: 中等

Related Topics: , 广度优先搜索, 二叉树

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

示例 1:

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

示例 2:

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

示例 3:

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

提示:

  • 树中节点数目在范围 [0, 2000]
  • -1000 <= Node.val <= 1000

Solution

Language: JavaScript

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
// 队列
var levelOrder = function(root) {
    const ans = []
    if (!root) return ans
    const q = []
    q.push(root) // 初始化队列
    while (q.length) {
        const len = q.length // 当前层节点的数量
        ans.push([]) // 新的层推入数组
        for (let i = 1; i <= len; i++) {
            const node = q.shift()
            // 推入当前层的数组
            ans[ans.length - 1].push(node.val)
            // 检查左节点,存在左节点就继续加入队列
            if (node.left) q.push(node.left)
            if (node.right) q.push(node.right)
        }
    }
    return ans
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions