剑指 Offer 32 - I. 从上到下打印二叉树
2022年5月24日
一、问题描述
从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回:
[3,9,20,15,7]
提示:
节点总数 <= 1000
二、问题分析
- 使用BFS进行广度优先搜索
- 引入队列实现BFS
- 注意对 root == NULL 的情况进行单独讨论
三、解题代码
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
que = collections.deque()
que.append(root)
res = []
while que:
root = que.popleft()
res.append(root.val)
if root.left is not None:
que.append(root.left)
if root.right is not None:
que.append(root.right)
return res
总结
使用队列实现BFS,注意特殊情况单独讨论。