Minimum Depth of Binary Tree in JavaScript

Xavier Carty
2 min readAug 28, 2020

Data Structures can be a bit challenging especially for someone who does not have a traditional CS Degree. However, anybody can get better at them with time and practice today I’m going to show you have to solve the minimum depth of a binary tree.

A binary tree is a tree data structure in which each node has at most two children, which are referred to as the left child and the right child. Finding the min depth of a binary tree is how deep a tree where we reach a leaf node. A leaf node is a node that has no children.

Let’s get started , you can do this whit depth first search or breadth first search. I use breadth first search because i want to visit each node on the same level first. You can do this recursively with DFS but it is up to you.

With BFS we use a queue. A queue is a LIFO data structure which is last in first out, we want to visit the node and its children. We also want to keep a total count of min Depth. We start at -1 because when we pop off the root it goes to zero the depth of the root is always zero we haven’t gone deep

function binary_tree_min_depth(root) {

let queue = []
queue.push(root)
let minDepth = -1
}

Now we need to iterate in the queue and push the child nodes in the queue. and increase the running total because while there is a node in the queue that means there is more depth

while(queue.length > 0){
minDepth++
let level = queue.length

Now here comes the meet of the code , we need to go level by level and get each subtrees children

let level = queue.length
for(let i = 0; i < level; i++){
let node = queue.shift()
//pop node off the queue
//if there are no left and right children thats our mindepth
if(!node.left && !node.right ){
return minDepth
}
//if there are more nodes to left and right add to queue
if(node.right !== null){
queue.push(node.right)
}
if(node.left !== null){
queue.push(node.left)
}

}
}

After all that is done we return minDepth

function binary_tree_min_depth(root) {
// WRITE YOUR BRILLIANT CODE HERE
let queue = []
queue.push(root)
let minDepth = -1
while(queue.length > 0){
minDepth++
let level = queue.length
for(let i = 0; i < level; i++){
let node = queue.shift()

if(!node.left && !node.right ){
return minDepth
}

if(node.right !== null){
queue.push(node.right)
}
if(node.left !== null){
queue.push(node.left)
}

}
}
return minDepth
}

That is! That is how you find the minimum depth of a binary tree in Javascript.

--

--

Xavier Carty

Learning new things everyday and sharing them with them world. Software Engineering , Muay Thai , and Soccer are my passions.