KatInterview

111. Minimum Depth of Binary Tree

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the minimum depth of a binary tree. The minimum depth is defined as the number of nodes along the shortest path from the root node down to the nearest leaf node. A key part of the definition is the term "leaf node," which is a node with no children. This distinction is crucial because it differentiates this problem from finding the maximum depth. For a node with only one child, we cannot stop; we must continue down that path to find a true leaf node.

Solution

Minimum Depth of Binary Tree in Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
from collections import deque
from typing import Optional

class Solution:
    def minDepth(self, root: Optional[TreeNode]) -> int:
        # If the tree is empty, its depth is 0.
        if not root:
            return 0

        # Use a deque for an efficient queue in BFS.
        queue = deque([root])
        # Start with depth 1 for the root level.
        depth = 1

        while queue:
            # Number of nodes at the current level.
            level_size = len(queue)

            # Process all nodes at the current level.
            for _ in range(level_size):
                node = queue.popleft()

                # If this is a leaf node (no children), we have found the minimum depth.
                if not node.left and not node.right:
                    return depth
                
                # Add non-null children to the queue for the next level.
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            
            # Increment depth after processing the entire level.
            depth += 1
        
        return 0 # Should not be reached

Minimum Depth of Binary Tree in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
import java.util.LinkedList;
import java.util.Queue;

class Solution {
    public int minDepth(TreeNode root) {
        // If the tree is empty, its depth is 0.
        if (root == null) {
            return 0;
        }

        // Use a queue for Breadth-First Search (BFS).
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        // Start with depth 1 for the root level.
        int depth = 1;

        while (!queue.isEmpty()) {
            // Number of nodes at the current level.
            int levelSize = queue.size();

            // Process all nodes at the current level.
            for (int i = 0; i < levelSize; i++) {
                TreeNode currentNode = queue.poll();

                // If this is a leaf node (no children), we have found the minimum depth.
                if (currentNode.left == null && currentNode.right == null) {
                    return depth;
                }

                // Add non-null children to the queue for the next level.
                if (currentNode.left != null) {
                    queue.offer(currentNode.left);
                }
                if (currentNode.right != null) {
                    queue.offer(currentNode.right);
                }
            }
            // Increment depth after processing the entire level.
            depth++;
        }
        
        return 0; // Should not be reached for a valid tree.
    }
}

Minimum Depth of Binary Tree in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
#include <queue>

class Solution {
public:
    int minDepth(TreeNode* root) {
        // If the tree is empty, its depth is 0.
        if (!root) {
            return 0;
        }

        // Use a queue for Breadth-First Search (BFS).
        std::queue<TreeNode*> q;
        q.push(root);
        // Start with depth 1 for the root level.
        int depth = 1;

        while (!q.empty()) {
            // Number of nodes at the current level.
            int level_size = q.size();

            // Process all nodes at the current level.
            for (int i = 0; i < level_size; ++i) {
                TreeNode* node = q.front();
                q.pop();

                // If this is a leaf node (no children), we have found the minimum depth.
                if (!node->left && !node->right) {
                    return depth;
                }

                // Add non-null children to the queue for the next level.
                if (node->left) {
                    q.push(node->left);
                }
                if (node->right) {
                    q.push(node->right);
                }
            }
            
            // Increment depth after processing the entire level.
            depth++;
        }

        return 0; // Should not be reached for a valid tree, but needed for compilation.
    }
};

Minimum Depth of Binary Tree in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function minDepth(root: TreeNode | null): number {
    // If the tree is empty, its depth is 0.
    if (!root) {
        return 0;
    }

    // Use an array as a queue for Breadth-First Search (BFS).
    const queue: TreeNode[] = [root];
    // Start with depth 1 for the root level.
    let depth = 1;

    while (queue.length > 0) {
        // Number of nodes at the current level.
        const levelSize = queue.length;

        // Process all nodes at the current level.
        for (let i = 0; i < levelSize; i++) {
            // Dequeue the node. The non-null assertion (!) is safe because we check queue.length > 0.
            const node = queue.shift()!;

            // If this is a leaf node (no children), we have found the minimum depth.
            if (!node.left && !node.right) {
                return depth;
            }

            // Add non-null children to the queue for the next level.
            if (node.left) {
                queue.push(node.left);
            }
            if (node.right) {
                queue.push(node.right);
            }
        }
        
        // Increment depth after processing the entire level.
        depth++;
    }

    return 0; // Should not be reached for a valid tree.
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.