Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the next level and alternate between).
For example: Given binary tree [3,9,20,null,null,15,7],
1 2 3 4 5
3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
1 2 3 4 5
[ [3], [20,9], [15,7] ]
Solution1 BFS+ Deque:
Use a deque to store the elements. The idea is to change direction of push elements into the deque and pop elements from deque.
# 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 classSolution: defzigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: ifnot root: return [] q, res, d = deque([]), [], True # True: look from right to left # False: look from left to right q.append(root) while q: pre_level_size = len(q) level = [] for _ in range(pre_level_size): if d: # cur level pop from right, append next level from left # pop from right so we would the rightest node as first one tmp = q.pop() if tmp.left: q.appendleft(tmp.left) if tmp.right: q.appendleft(tmp.right) else: # cur level pop from left, append next level from right # pop from left so we would the leftest node as first one tmp = q.popleft() if tmp.right: q.append(tmp.right) if tmp.left: q.append(tmp.left) level.append(tmp.val) d = not d res.append(level) return res