103. Binary Tree Zigzag Level Order Traversal
My accepted JavaScript solution to LeetCode problem 103, Binary Tree Zigzag Level Order Traversal, running in 0ms.
- Difficulty: Medium
- JavaScript
- Runtime 0ms
- Memory 54.6MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
JavaScript
Accepted on LeetCode — runtime 0ms, memory 54.6MB, accepted 2025-12-24.
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var zigzagLevelOrder = function(root) {
if (!root) return [];
const result = [];
const queue = [root];
let leftToRight = true;
while (queue.length > 0) {
const levelSize = queue.length;
const level = [];
for (let i = 0; i < levelSize; i++) {
const node = queue.shift();
if (leftToRight) {
level.push(node.val);
} else {
level.unshift(node.val);
}
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
result.push(level);
leftToRight = !leftToRight;
}
return result;
};