JavaScript || Easy and well explained code
Explanation:\n\n1. If the root is null, return an empty array.\n1. Initialize a result array result, a queue q to store nodes and a level counter level.\n1. Whi
# Explanation:\n\n1. If the root is null, return an empty array.\n1. Initialize a result array result, a queue q to store nodes and a level counter level.\n1. While the queue q is not empty, do the following:\n1. Get the size of the queue, and initialize an array currLevel to store the current level\'s values.\n1. Loop size times, dequeue the first node node from the queue, push its value to currLevel.\n1. If node has a left child, add it to the queue q.\n1. If node has a right child, add it to the queue q.\n1. If the level is odd, reverse currLevel, and push it to the result array.\n1. Increment the level counter level.\n1. Return the result array.\n- This solution has a time complexity of O(n) and a space complexity of O(n), where n is the number of nodes in the tree.\n\n\n\n\n\n# Code\n```\nvar zigzagLevelOrder = function(root) {\n    if (!root) return [];\n    \n    let result = [], q = [root], level = 0;\n    \n    while (q.length) {\n        let size = q.length, currLevel = [];\n        for (let i = 0; i < size; i++) {\n            let node = q.shift();\n            currLevel.push(node.val);\n            if (node.left) q.push(node.left);\n            if (node.right) q.push(node.right);\n        }\n        if (level % 2 === 1) currLevel.reverse();\n        result.push(currLevel);\n        level++;\n    }\n    return result;\n};\n\n```\n\nThere are several ways to optimize this solution further:\n\n- Reusing the same array for different levels, instead of creating a new array for each level. This will reduce the memory footprint of the solution.\n\n- Using a queue for the breadth-first search, instead of recursion. This will reduce the call stack size and avoid the risk of stack overflow for large trees.\n\n- Using a stack for reversing the order of the levels, instead of reversing the array after each level. This will reduce the time complexity and the memory usage of the solution.\n
['Tree', 'Breadth-First Search', 'Binary Tree', 'JavaScript']