Minimum Depth of Binary Tree
Easy
TreeBFSDFS
Problem
Return the minimum depth — the number of nodes along the shortest root-to-leaf path.
Example 1
Input: [3,9,20,null,null,15,7]
Output: 2
Constraints
- 0 ≤ nodes ≤ 10⁵
Approach — Tree Traversal
This is a Tree Traversal problem. The idea: traverse the tree — DFS recursively, or BFS level by level — and combine the results from each subtree. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) time.
Solution code
Python
class Solution:
def minDepth(self, root):
if not root:
return 0
if not root.left:
return 1 + self.minDepth(root.right)
if not root.right:
return 1 + self.minDepth(root.left)
return 1 + min(self.minDepth(root.left), self.minDepth(root.right))
Java
class Solution {
public int minDepth(TreeNode root) {
if (root == null) return 0;
// Layered BFS — the FIRST leaf we meet is the shallowest one,
// so we can stop immediately (DFS would walk the whole tree).
Queue<TreeNode> q = new ArrayDeque<>();
q.add(root);
int depth = 1;
while (!q.isEmpty()) {
int size = q.size(); // freeze one whole layer
for (int i = 0; i < size; i++) {
TreeNode cur = q.poll();
if (cur.left == null && cur.right == null) return depth;
if (cur.left != null) q.add(cur.left);
if (cur.right != null) q.add(cur.right);
}
depth++;
}
return depth;
// DFS alternative (watch the trap — a node with ONE child is
// not a leaf, so you can't just take min of both sides):
// if (root.left == null) return 1 + minDepth(root.right);
// if (root.right == null) return 1 + minDepth(root.left);
// return 1 + Math.min(minDepth(root.left), minDepth(root.right));
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Minimum Depth of Binary Tree interactively → ← All solutions