无聊的刷题笔记

从上到下打印二叉树-II

剑指Offer 32-3

请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。

例如:
给定二叉树: [3,9,20,null,null,15,7],

3

/ \
9 20
/ \
15 7
返回其层次遍历结果:

[
[3],
[20,9],
[15,7]
]

提示:

节点总数 <= 1000

# 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 = [[root],[]]
num = 0
result = []
while len(queue[0])!=0 or len(queue[1])!=0:
level = []
while len(queue[num]) != 0:
node = queue[num].pop(0)
level.append(node.val)
if node.left:
queue[1-num].append(node.left)
if node.right:
queue[1-num].append(node.right)
if num == 1:
level = list(reversed(level))
result.append(level)
num = 1 - num
return result