LeetCode Entry
111. Minimum Depth of Binary Tree
Count nodes in the shortest path from root to leaf
111. Minimum Depth of Binary Tree easy
blog post
substack

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/271
Problem TLDR
Count nodes in the shortest path from root to leaf
Intuition
- remember to count
nodes, notedges leafis a node without children- use BFS or DFS
Approach
Let’s use BFS
Complexity
-
Time complexity: \(O(n)\)
-
Space complexity: \(O(n)\)
Code
fun minDepth(root: TreeNode?): Int = with(ArrayDeque<TreeNode>()) {
root?.let { add(it) }
generateSequence(1) { (it + 1).takeIf { isNotEmpty() } }
.firstOrNull {
(1..size).any {
with(poll()) {
left?.let { add(it) }
right?.let { add(it) }
left == null && right == null
}
}
} ?: 0
}