1

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

5
  • 1
    Probably because it might be 0 or falsey Commented Nov 25, 2022 at 5:26
  • 0 or false is == undefined of q[0] they both should break the loop no? Commented Nov 25, 2022 at 5:29
  • No, [0] will still have length 1, for example Commented Nov 25, 2022 at 5:31
  • leetcode.com/problems/binary-tree-level-order-traversal/… Commented Nov 25, 2022 at 5:59
  • It looks like it’s just a shorter way of saying, “while q is not empty”, on the assumption that falsy values will not be in q (it contains objects) and that q is dense. Commented Nov 25, 2022 at 6:00

2 Answers 2

2

What is happening with the while(q[0]) check is that the author is making sure that the array is not empty since an item is removed on every iteration by calling q.shift(). Array.prototype.shift() removes the leftmost element from an array and is a mutable method.

It is more practical to know that each element is not empty as the input could be an array of arrays because otherwise, you would have to go through every element and calculate its length.

Sign up to request clarification or add additional context in comments.

3 Comments

if I understand correctly, he wants to make sure that q doesn't have an empty array? such as [[]] ? in this case both q[0] and q.length will are truthy no? I am still not getting it. Also q.shift() remove the left most element no?
Array#shift will remove leftmost element.
My apologies. You are correct in that Array.shift() will remove the leftmost element and mutate the original array. I corrected my answer to compensate my mistake.
-1

Somone answered the question in leet and I am reposting it so others can benifit

Because root could be null, in which case we should skip the while loop and proceed to return ans even though q.length = 1.

Alternatively, we could insert the line if (!root) return [] before the while loop (similar to the C++ or Java solutions), or changed the q definition to q = root ? [root] : [] (similar to the Python solution).

credit to sgallivan

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.