動機

因為102的走是用level來分,所以這裡當輸出改變的時候就不用改太多

Problem

Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).

 

Example 1:

Input: root = [3,9,20,null,null,15,7]Output: [[3],[20,9],[15,7]]

Example 2:

Input: root = [1]Output: [[1]]

Example 3:

Input: root = []Output: []

 

Constraints:

  • The number of nodes in the tree is in the range [0, 2000].
  • -100 <= Node.val <= 100

Sol

把102的copy過來,在輸出答案時決定要不要reverse

class Solution:
    def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root:
            return []
        q = deque([[root]])
        ret = []
        rev = False
        while q:
            now = []
            rs = q.popleft()
            ret.append([r.val for r in (rs if not rev else rs[::-1])])
            for r in rs:
                now += [x for x in [r.left,r.right] if x]
            if len(now) > 0:
                q.append(now)
            rev = not rev
        return ret