Minimum Depth Of Binary Tree Problem
Description
LeetCode Problem 111.
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.
Note: A leaf is a node with no children.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: 2
Example 2:
Input: root = [2,null,3,null,4,null,5,null,6]
Output: 5
Constraints:
- The number of nodes in the tree is in the range [0, 10^5].
- -1000 <= Node.val <= 1000
Solution
Approach: Breadth-First Search
Breadth-first search visits the tree level by level, from the root down. The first leaf it reaches is therefore on the shallowest level that has a leaf, and its level is the answer. The search can stop right there, without looking at the deeper parts of the tree.
- If the tree is empty, return 0.
- Start with
current = [root]anddepth = 1. - Go through the nodes of
current. If a node has no children, returndepth. Otherwise add its existing children tonext. - Continue with
current = nextanddepth + 1.
The one detail people get wrong is the definition of a leaf. A node with only one child is not a leaf, so a missing child must not count as a path of length 0. The tempting recursion 1 + min(minDepth(left), minDepth(right)) makes exactly this mistake. For [2,null,3,null,4,null,5,null,6] it returns 1, because the root's empty left side gives 0, but the only leaf is 6 and the answer is 5. Checking that both children are missing, as in step 3, avoids the problem.
BFS is also faster than a depth-first walk when a shallow leaf exists in a large tree, because it never explores below that leaf's level.
Complexity: O(n) time and O(n) space in the worst case, where n is the number of nodes: each node is visited at most once, and one level of the tree is stored at a time.
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
depth = 1
current = [root] # the nodes at this depth
while True:
next_level = []
for node in current:
if node.left is None and node.right is None:
return depth # levels go top-down, so the first leaf is the closest one
if node.left is not None:
next_level.append(node.left)
if node.right is not None:
next_level.append(node.right)
current = next_level
depth += 1
Now write it from memory
Close the write-up and solve it yourself against the tests.