Skip to content

Latest commit

 

History

History
34 lines (31 loc) · 894 Bytes

2023-02-19.md

File metadata and controls

34 lines (31 loc) · 894 Bytes

题目

  1. Binary Tree Zigzag Level Order Traversal

Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).

思路

代码

// runtime 83.71% memory 97.94%
var zigzagLevelOrder = function(root) {
  if (root == null) return []
  const res = []
  const queue = [root]
  let depth = 1
  while (queue.length) {
    const length = queue.length
    const nodes = queue.splice(0, length)
    const values = []
    for (let i = 0; i < length; i++) {
      values.push(nodes[i].val)
      if (nodes[i].left != null) queue.push(nodes[i].left)
      if (nodes[i].right != null) queue.push(nodes[i].right)
    }
    if (depth % 2 == 1) {
      res.push(values)
    } else {
      res.push(values.reverse())
    }
    depth++
  }
  return res
}