111. Minimum Depth of Binary Tree
https://leetcode.com/problems/minimum-depth-of-binary-tree/
Python
DFS Postfix
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
def dfs(node):
if not node:
return 0
if node.right is None:
return dfs(node.left) + 1
if node.left is None:
return dfs(node.right) + 1
left, right = dfs(node.left), dfs(node.right)
return min(left, right) + 1
return dfs(root)
BFS
from collections import deque
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
level, queue = 0, deque([root])
while queue:
level += 1
for _ in range(len(queue)):
node = queue.popleft()
if not node.left and not node.right:
return level
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)