-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path94.py
51 lines (36 loc) · 1.21 KB
/
94.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
51
# 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
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
result = []
if not root:
return result
# Traversal - BFS
# reverse the list for every alternative level
# append it to the list
queue = deque()
queue.append(root)
# flag to reverse the level list
isReverse = False
while queue:
size = len(queue)
level = deque()
for _ in range(size):
node = queue.popleft()
if isReverse:
level.appendleft(node.val)
else:
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
# inverting the flag value as we need to reverse for alternative level
isReverse = not isReverse
result.append(level)
return result