-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path6. ZigZag.py
50 lines (42 loc) · 1.5 KB
/
6. ZigZag.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
50
# 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 collections import deque
from typing import Optional
class Solution:
def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: # type: ignore
if not root:
return []
q = deque([(root, 0)])
curr_arr = []
finalarr = []
curr_level = 0
booleanFlag = True
while q:
curr, l = q.popleft()
if l > curr_level and booleanFlag:
finalarr.append(curr_arr)
curr_arr = []
curr_level = l
booleanFlag = False
elif l > curr_level and not booleanFlag:
finalarr.append(curr_arr[::-1])
curr_arr = []
curr_level = l
booleanFlag = True
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 and booleanFlag:
finalarr.append(curr_arr)
booleanFlag = False
elif curr_arr and not booleanFlag:
finalarr.append(curr_arr[::-1])
booleanFlag = True
return finalarr
# Link: https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/