Skills101
← All coding problems

Minimum Depth of Binary Tree

easyTrees & BST II+10 XPTime limit 2s

The minimum depth of a tree is the number of nodes on the shortest path from the root to a leaf (a node with no children). Find it.

Tree format. A binary tree is given on one line in level order (top to bottom, left to right), with null for a missing child — the same way most interview platforms show trees. Trailing nulls are left out, and an empty tree is the single word null. Example: 3 9 20 null null 15 7 is

    3
   / \
  9   20
     /  \
    15   7

Input: one tree.

Output: the minimum depth (0 for an empty tree).

Constraints: 0 ≤ nodes ≤ 10⁴. The tree has at most 10⁴ nodes and its height is at most 500, so recursion is safe in every language.

Watch out: in 1 null 2 the root is not a leaf (it has a right child), so the answer is 2, not 1. A plain 1 + min(left, right) gets this wrong. BFS is the natural fit: the first leaf you meet level by level is the answer, and you can stop early.

Sample input 1

3 9 20 null null 15 7

Sample output 1

2

Sample input 2

2 null 3 null 4 null 5 null 6

Sample output 2

5

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.