Minimum Depth of Binary Tree

Easy

This is an extra practice problem. It doesn't have walkthrough slides. You can solve it with the pattern template you already know. Open the hints if you get stuck.

Question

Given the root of a binary tree, return the minimum depth. That's the number of nodes on the shortest path from the root down to a leaf.

A leaf is a node that has no children of its own.

Input: root = [8, 15, 25, None, None, 12, 6]

Output: 2

15 has no children, so it's a leaf. The path from 8 to 15 has 2 nodes. 25 isn't a leaf because it has children.

Input: root = [50, 30, 70]

Output: 2

Both 30 and 70 are leaves one step below the root.

Input: root = [20, 30]

Output: 2

20 isn't a leaf because it has a child. 30 is the only leaf. That means the shortest path goes from 20 down to 30.

Clarify the problem

What are some questions you'd ask an interviewer?

Understand the problem

Why is a plain min(left_depth, right_depth) + 1 formula risky for this problem?
It's fine. That formula always works.
A node with a single child can make that formula pick a side with no leaf at all.
It only breaks for empty trees.
It only breaks for trees with duplicate values.

Remember to understand the problem and plan your approach before you start coding.