剑指Offer32-II-从上到下打印二叉树
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:
给定二叉树: [3,9,20,null,null,15,7]
:
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
提示:
节点总数 <= 1000
来源:力扣(LeetCode)
链接:力扣
一解
使用广度遍历:
-
将同一层级树节点存储在 nodes 中
-
遍历 nodes ,取出“当前结点值”和“下一层树结点”
# 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 []
result, queue = [], collections.deque()
queue.append(root)
while queue:
nodes = []
while queue:
nodes.append(queue.popleft())
result.append([i.val for i in nodes])
for node in nodes:
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
return result
二解
思路与一解相同,由于for _ in range(len(queue))
的循环次数固定(len(queue)
),不会随queue
的大小进行变化(while queue
),因此可将queue.append
操作放入循环内:
# 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 []
result, queue = [], collections.deque()
queue.append(root)
while queue:
nodes = []
for _ in range(len(queue)):
node = queue.popleft()
nodes.append(node.val)
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
result.append(nodes)
return result