题目描述
从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
例如:
给定二叉树: [3,9,20,null,null,15,7],3
/ \
9 20
/ \
15 7返回:
32-1: [3,9,20,15,7]
32-2: [3,[9, 20],[15,7]]
32-3: [3,[20, 9],[15,7]]
解题思路: BFS+队列
这三个题目都是分层输出二叉树, 我们可以使用队列来实现BFS.
- 32-1直接输出元素
- 32-2则需要将每层构造成一个数组
- 32-3则是需要根据奇偶层判断, 整体思路不变.
示例代码
# 32-1
def levelOrder(self, root: TreeNode) -> List[int]:
if not root:
return []
res, queue = [], [root]
while queue:
temp = queue.pop(0)
res.append(temp.val)
if temp.left:
queue.append(temp.left)
if temp.right:
queue.append(temp.right)
return res
# 32-2
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
res, queue = [], [[root]]
while queue:
tempL, tempQ = [], [] # 每次大循环创建新的数组类保存当前层数据
firstQ = queue.pop(0)
while firstQ:
temp = firstQ.pop(0)
tempL.append(temp.val)
if temp.left: tempQ.append(temp.left)
if temp.right: tempQ.append(temp.right)
if tempL: res.append(tempL)
if tempQ: queue.append(tempQ)
return res
# 32-3
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
res, queue = [], [[root]]
while queue:
tempL, tempQ = [], [] # 每次大循环创建新的数组类保存当前层数据
firstQ = queue.pop(0)
while firstQ:
temp = firstQ.pop(0)
if len(res) % 2: # 根据奇偶层判断是加入最后还是插入前边
tempL.insert(0, temp.val)
else:
tempL.append(temp.val)
if temp.left: tempQ.append(temp.left)
if temp.right: tempQ.append(temp.right)
if tempL: res.append(tempL)
if tempQ: queue.append(tempQ)
return res