Binary Tree Zigzag Level Order Traversal

Medium#103tree nodes

Write down the values of a binary tree level by level, turning direction on every level: the top level left to right, the next one right to left, and so on. Our example: the tree [7, 4, 9, none, 5, 1, 11] in level order — the answer is [[7], [9, 4], [5, 1, 11]].

input
root: a binary tree, written as on LeetCode: its values level by level, left to right, null for a missing child.
returns
Its values level by level, a list per level from the root down: the root's level left to right, the next right to left, and so on, turning at each level; [] for an empty tree.
constraints
  • 0 ≤ the number of nodes ≤ 2000
  • −100 ≤ Node.val ≤ 100
our 11 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * 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[][]}
 */
function zigzagLevelOrder(root) {

}
Ctrl ↵
format
reset

saved in this browser

11 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more breadth-first search (bfs) problems

Pattern “Breadth-first search (BFS)” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.