-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy path0103.py
35 lines (31 loc) · 958 Bytes
/
0103.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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
import collections
if not root:
return []
res, q = [], collections.deque()
flag = False # 做奇偶判断
q.append(root)
while q:
temp = []
flag = not flag
for _ in range(len(q)):
node = q.popleft()
# 头插
if flag:
temp.append(node.val)
# 尾插
else:
temp.insert(0, node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
res.append(temp)
return res