-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path102.py
30 lines (27 loc) · 885 Bytes
/
102.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
# https://neetcode.io/problems/level-order-traversal-of-binary-tree
# https://leetcode.com/problems/binary-tree-level-order-traversal/description/
# 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
from typing import Optional, List
from collections import deque
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
q = deque([root])
res = []
while q:
newQ = deque()
newLi = []
while q:
n = q.popleft()
if n:
newLi.append(n.val)
newQ.append(n.left)
newQ.append(n.right)
if newLi:
res.append(newLi)
q = newQ
return res