-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path#0111 Minimum Depth of Binary Tree.py
49 lines (39 loc) · 1.43 KB
/
#0111 Minimum Depth of Binary Tree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
from typing import Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
"""
Returns the minimum depth of a binary tree.
The minimum depth is the number of nodes along the shortest path from
the root node down to the nearest leaf node.
Args:
root (Optional[TreeNode]): The root node of the binary tree.
Returns:
int: The minimum depth of the binary tree.
"""
if not root:
return 0
# Initialize a queue for breadth-first search (BFS)
queue = [root]
depth = 1
# Perform BFS
while queue:
# Iterate over all nodes at the current depth
for _ in range(len(queue)):
n = queue.pop(0)
# Check if the current node is a leaf node
if not n.left and not n.right:
return depth
# Add child nodes to the queue
if n.left:
queue.append(n.left)
if n.right:
queue.append(n.right)
# Increment the depth after processing the current level
depth += 1
return 0