Hone logo
Hone
Problems

Minimum Depth of a Binary Tree

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. A leaf node is a node with no children. This problem is fundamental for understanding tree traversal and optimization.

Problem Description

Your task is to implement a function that calculates the minimum depth of a given binary tree. The depth is defined as the number of nodes from the root to a leaf. You need to find the path with the fewest nodes that ends at a leaf.

Requirements:

  • Traverse the binary tree.
  • Identify leaf nodes.
  • Determine the shortest path from the root to any leaf node.
  • Return the length of this shortest path (number of nodes).

Edge Cases:

  • An empty tree (root is null).
  • A tree with only a root node.
  • A tree where one branch is significantly shorter than others.

Examples

Example 1:

Input:
    3
   / \
  9  20
    /  \
   15   7

Output: 2
Explanation: The shortest path from the root to a leaf is 3 -> 9, which has a length of 2 nodes.

Example 2:

Input:
    2
     \
      3
       \
        4
         \
          5
           \
            6

Output: 5
Explanation: The shortest path from the root to a leaf is 2 -> 3 -> 4 -> 5 -> 6, which has a length of 5 nodes.

Example 3:

Input:
    1
   /
  2

Output: 2
Explanation: The shortest path from the root to a leaf is 1 -> 2, which has a length of 2 nodes.

Constraints

  • The number of nodes in the tree will be between 0 and 10^5.
  • Node values are integers.
  • Your solution should aim for an efficient time complexity, ideally O(N) where N is the number of nodes in the tree.

Notes

  • A null tree should have a minimum depth of 0.
  • Consider how you might handle nodes that have only one child.
  • Think about different traversal strategies (e.g., Breadth-First Search vs. Depth-First Search) and which might be more suitable for finding the minimum depth.
Loading editor...
plaintext