Skip to content

103. 二叉树的锯齿形层序遍历 #31

@webVueBlog

Description

@webVueBlog

103. 二叉树的锯齿形层序遍历

Description

Difficulty: 中等

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

给你二叉树的根节点 root ,返回其节点值的 锯齿形层序遍历 。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。

示例 1:

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

示例 2:

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

示例 3:

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

提示:

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

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 zigzagLevelOrder = function(root) {
    if (!root) return []
    const ans = []
    const nodeQueue = [root]

    let isOrderLeft = true

    while (nodeQueue.length) {
        let levelList = []
        const size = nodeQueue.length
        for (let i = 1; i <= size; i++) {
            const node = nodeQueue.shift()
            if (isOrderLeft) {
                levelList.push(node.val)
            } else {
                levelList.unshift(node.val)
            }
            if (node.left) nodeQueue.push(node.left)
            if (node.right) nodeQueue.push(node.right)
        }
        ans.push(levelList)
        isOrderLeft = !isOrderLeft
    }

    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