# # 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: Optional[TreeNode]) -> List[List[int]]: ans = [] ifReverse = False q = [] if root: q.append(root) while q: ans.append([]) for _ inrange(len(q)): thisNode = q[0] q = q[1:] ans[-1].append(thisNode.val) if thisNode.left: q.append(thisNode.left) if thisNode.right: q.append(thisNode.right) if ifReverse: ans[-1].reverse() ifReverse = not ifReverse return ans