Javascript Detailed line-by-line solution
We can use an inner for loop at each iteration of the while loop. When the loop begins, the length of the queue represents the # of nodes at the level. So by ex
We can use an inner for loop at each iteration of the while loop. When the loop begins, the length of the queue represents the # of nodes at the level. So by exhausting this length, we will only push the nodes into the queue that are all at the same level. The table below helped me understand a bit better whats going on.\n\nFor example:\nGiven binary tree [3,9,20,4,1,5,7,null,null,2,null,null,null],\n```\n\n               3\n           \u2571       \u2572\n         \u2199            \u2198\n       9                20\n     \u2199   \u2198           \u2199    \u2198\n   4       1        5       7\n \u2199  \u2198    \u2199  \u2198    \u2199  \u2198    \u2199  \u2198\n                2\nLevel Order Traversal = [[3], [9,20], [4,1,5,7], [2]]\n```\n\nCurrent | i < | qLength |   queue   | currLevel |         levels\n------- | --- | ------- | --------- | --------- | ----------------------\n3       | 0   | 1       | [9,20]    | [3]       | [[3]]\n9       | 0   | 2       | [20,4,1]  | [9]       | [3]\n20      | 1   | 2       | [4,1,5,7] | [9,20]    | [[3],[9,20]]\n4       | 0   | 4       | [1,5,7]   | [4]       | [[3],[9,20]]\n1       | 1   | 4       | [5,7]     | [4,1]     | [[3],[9,20]]\n5       | 2   | 4       | [7,2]     | [4,1,5]   | [[3],[9,20]]\n7       | 3   | 4       | [2]       | [4,1,5,7] | [[3],[9,20],[4,1,5,7]]\n2       | 0   | 1       | []        | [2]       | [[3],[9,20],[4,1,5,7],[2]]\n\n**Code:**\n```\nvar levelOrder = function(root) {\n    // If root is null return an empty array\n    if(!root) return []\n    \n    const queue = [root] // initialize the queue with root\n    const levels = [] // declare output array\n    \n    while(queue.length !== 0){\n       const queueLength = queue.length // Get the length prior to dequeueing\n       const currLevel = [] // Declare this level\n       // loop through to exhaust all options and only to include nodes at currLevel\n       for(let i = 0; i < queueLength; i++){\n           // Get next node\n           const current = queue.shift()\n           \n           if(current.left){\n               queue.push(current.left)\n           }\n           if(current.right){\n               queue.push(current.right)\n           }\n           // After we add left and right for current, we add to currLevel\n           currLevel.push(current.val)\n       }\n       // Level has been finished. Push into output array\n       levels.push(currLevel)\n   }\n    return levels\n}\n```
['Breadth-First Search', 'Iterator', 'JavaScript']