Skip to main content

Minimum Depth of Binary Tree

Problem

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Note: A leaf is a node with no children.

 

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: 2

Example 2:

Input: root = [2,null,3,null,4,null,5,null,6]
Output: 5

 

Constraints:

  • The number of nodes in the tree is in the range [0, 105].
  • -1000 <= Node.val <= 1000

Solution

/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var minDepth = function(root) {
if (!root) {
return 0;
} else if (root.left && root.right) {
return 1 + Math.min(minDepth(root.left), minDepth(root.right));
} else {
return 1 + minDepth(root.left ?? root.right);
}
};

We use standard DFS to find the minimum depth of the tree root.

Optimization

A far better and more optimized solution is to use BFS, since DFS needs to traverse every branch of the tree before terminating (BFS does not).

/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var minDepth = function(root) {
let depth = 0;
const queue = root ? [root] : [];

while (queue.length) {
depth++;
const n = queue.length;
for (let i = 0; i < n; i++) {
const node = queue.shift();

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

We do a level order traversal using BFS, and return the current depth when a leaf node is found.