AFFILIATE LINKS
Great resource I use to learn algorithms.
40% off Tech Interview Pro: http://techinterviewpro.com/terriblewhiteboard
20% off CoderPro: http://coderpro.com/terriblewhiteboard
Here is the full implementation.
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
let minDepth = function(root) {
if (root === null) {
return 0;
}
let queue = [];
queue.push(root);
let depth = 0;
while (queue.length !== 0) {
let numberOfNodes = queue.length;
while (numberOfNodes > 0) {
let currentNode = queue.shift();
if (currentNode.left === null && currentNode.right === null) {
depth++;
return depth;
}
if (currentNode.left !== null) {
queue.push(currentNode.left);
}
if (currentNode.right !== null) {
queue.push(currentNode.right);
}
numberOfNodes--;
}
depth++;
}
};