0

I stumbled upon a solution,

var minDepth = function(root) {
if(!root) return 0;
let depth = 1;
let queue = [root];
if(!root.left && !root.right) return depth;

while(queue.length > 0 ){
  let queueLength = queue.length;

  for(let i = 0; i < queueLength; i++){
    let node = queue.shift();

    if(!node.left && !node.right) return depth;
    else{
      if(node.left) queue.push(node.left);
      if(node.right) queue.push(node.right);
    }
  }

  depth++;
}

return depth;
};

This code gives wrong answer without assigning the queue length to a variable.

let queueLength = queue.length;

  for(let i = 0; i < queueLength; i++) ...

What is going on here?

Example: Input - [3, 9, 20, null, null, 15, 7]

Output: with the variable - 2 (right)

without the var - 1

Amir
  • 1,328
  • 2
  • 13
  • 27

1 Answers1

1

This is because the length of queue is dynamic and changing constantly. Let's take an example of your question. first you will add 3 to queue here what happens:-

before first iteration queue = [3], queue.length = 1 and i = 0

depth should increase after first iteration but see what happens.

after 1st iteration of loop queue = [9, 20], queue.length = 2 and i = 1

Here it should stop because it have checked all the values in same level (which is in this case is root node which is 3) but it continues as queue.length > i

after 2nd iteration of loop queue = [20], queue.length = 1 and i = 2

as queue.length < i, loop will break and depth will increase but depth should increase after we added all the child to the queue this is why it's giving wrong answer. So you should add queue.length to var so that number of iterations we want to do does not change.