-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0111-minimum-depth-of-binary-tree.py
More file actions
42 lines (36 loc) · 1.05 KB
/
0111-minimum-depth-of-binary-tree.py
File metadata and controls
42 lines (36 loc) · 1.05 KB
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
# time complexity: O(n)
# space complexity: O(n)
from collections import deque
from typing import Optional
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:
q = deque()
q.append(root)
level = 0
minLevel = 100000
if root is None:
return 0
while q:
level += 1
for _ in range(len(q)):
node = q.popleft()
if node is None:
break
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
if node.left is None and node.right is None:
minLevel = min(minLevel, level)
return minLevel
root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right.left = TreeNode(15)
root.right.right = TreeNode(7)
print(Solution().minDepth(root))