Binary Tree Zigzag Level Order Traversal
Given the root of a binary tree, return its values level by level in zigzag order: the first level from left to right, the second from right to left, the third from left to right again, and so on, alternating at every level.
The result is an array of arrays, one inner array per level, top level first. Return an empty array for an empty tree.
Constraints
- The tree has between
0and2000nodes. -100 <= Node.val <= 100
Examples
Example 1
Input: root = [1,2,3,4,5,6,7] Output: [[1],[3,2],[4,5,6,7]]
Level 1 left to right: [1]. Level 2 right to left: [3, 2]. Level 3 left to right again: [4, 5, 6, 7].
Example 2
Input: root = [1] Output: [[1]]
One level, read left to right.
Example 3
Input: root = [] Output: []
No nodes, no levels.
JavaScript you'll use: Stacks, queues and deques Arrays: create, read, update
/**
* Tree nodes are provided (you don't need to define them):
* class TreeNode { constructor(val = 0, left = null, right = null) { this.val = val; this.left = left; this.right = right; } }
*/
/**
* @param {TreeNode | null} root
* @return {number[][]}
*/
function zigzagLevelOrder(root) {
}
Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.