LeetCode-103. 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).

Example :

img

1
2
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[20,9],[15,7]]

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
* @Description: 103. Binary Tree Zigzag Level Order Traversal
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* 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[][]}
*/
const zigzagLevelOrder = function(root) {
if (!root) {
return []
}

let queue = [root]
let res = []
let leftToRight = true

while (queue.length) {
let curLength = queue.length
let curLevel = []

for (let i = 0; i < curLength; i++) {
let cur = queue.shift()
if (leftToRight) {
curLevel.push(cur.val)
} else {
curLevel.unshift(cur.val)
}
if (cur.left) {
queue.push(cur.left)
}
if (cur.right) {
queue.push(cur.right)
}
}
leftToRight = !leftToRight
res.push(curLevel)
}
return res
}