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:
Given binary tree [3,9,20,null,null,15,7],
1 | 3 |
return its minimum depth = 2.
Attempt
We can traverse tree and record the min depth among leaf nodes.
1 | /** |
Aha! I need to read the question more carefully 😧 I need to count the number of nodes!!! Additionally, we need to exclude the paths where a leaf may be missing, since that would skew the result! This is a pretty good problem, even though it’s marked as easy. I also don’t need to add a separate recursive function. We can just use the given function recursively.
Accepted
1 | /** |