链接:剑指 Offer 32 - III. 从上到下打印二叉树 III
层次遍历二叉树的基础上每次用一个数组保存当前层的结点,然后按照奇偶层进行反序就好了
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
queue = collections.deque()
queue.append(root)
res = []
cnt = 1
while queue:
tmp = []
size = len(queue)
for _ in range(size):
q = queue.popleft()
tmp.append(q.val)
if q.left:
queue.append(q.left)
if q.right:
queue.append(q.right)
if cnt == 1:
res.append(tmp)
else:
res.append(tmp[::-1])
cnt = -cnt
return res