AcWing 45. 之字形打印二叉树-py
原题链接
中等
from collections import deque
class Solution(object):
def printFromTopToBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
res = []
reverse = False # 初始开关
queue = deque([root])
while queue:
level = []
for _ in range(len(queue)):
node = queue.popleft()
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
if reverse: # 第一层不用反转
level.reverse()
reverse = not reverse
res.append(level)
return res