Home > Net >  Confused about iterating while array[] vs while array.length
Confused about iterating while array[] vs while array.length

Time:11-25

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

CodePudding user response:

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 rightmost 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.

CodePudding user response:

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

  • Related