-
Notifications
You must be signed in to change notification settings - Fork 0
/
8. LevelOrder.py
39 lines (31 loc) · 1.06 KB
/
8. LevelOrder.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
from collections import deque
from typing import Optional, List
# 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 levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
q = deque([(root, 0)])
curr_arr = []
finalarr = []
curr_level = 0
while q:
curr, l = q.popleft()
if l > curr_level:
finalarr.append(curr_arr)
curr_arr = []
curr_level = l
curr_arr.append(curr.val)
if curr.left:
q.append((curr.left, l + 1)) # type: ignore
if curr.right:
q.append((curr.right, l + 1)) # type: ignore
if curr_arr:
finalarr.append(curr_arr)
return finalarr
# Link: https://leetcode.com/problems/binary-tree-level-order-traversal/submissions/1300965130/