Minimum Depth of Binary Tree
Problem: Minimum Depth of Binary Tree
We can do breadth-first search to find the nearest leaf node. During the search, we can record the depth of each level so that once we find a leaf node we can immediately return the answer.
Code in Python:
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root: return 0
ans, currentLevel = 1, [root]
while currentLevel:
nextLevel = []
for node in currentLevel:
if not node.left and not node.right: return ans
if node.left: nextLevel.append(node.left)
if node.right: nextLevel.append(node.right)
ans, currentLevel = ans + 1, nextLevel
return ans