so I was working on this leet code problem.
and here is the solution
var levelOrder = function(root) {
let q = [root], ans = []
while (q[0]) {
let qlen = q.length;
let row = [];
for (let i = 0; i < qlen; i++) {
let curr = q.shift()
row.push(curr.val)
if (curr.left) q.push(curr.left)
if (curr.right) q.push(curr.right)
}
ans.push(row)
}
return ans
};
However, I am confused about the while loop. Why does it work when it's while (q[0]) {
and not when I use while (q.length) {
it's pretty much the same thing no? could anyone help me understand? Thanks
[0]will still have length 1, for example