无聊的刷题笔记

从上到下打印二叉树-II

剑指Offer 32-2

从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。

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

  3
/ \
9 20
/ \
15 7

返回其层次遍历结果:

[
[3],
[9,20],
[15,7]
]
# 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)
result.append(level)
num = 1 - num
return result