题目:
题解:
class Solution:def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:if not root: return []res, deque = [], collections.deque()deque.append(root)while deque:tmp = []# 打印奇数层for _ in range(len(deque)):# 从左向右打印node = deque.popleft()tmp.append(node.val)# 先左后右加入下层节点if node.left: deque.append(node.left)if node.right: deque.append(node.right)res.append(tmp)if not deque: break # 若为空则提前跳出# 打印偶数层tmp = []for _ in range(len(deque)):# 从右向左打印node = deque.pop()tmp.append(node.val)# 先右后左加入下层节点if node.right: deque.appendleft(node.right)if node.left: deque.appendleft(node.left)res.append(tmp)return res