102.给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
- BFS解题思路:明显的广度优先遍历,但主要的难点在于如何在遍历的过程中记录节点的层数,关键在于节点出队列的时候锁定当前层的节点数,锁定后入队的节点就不会收到影响
# 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]
level_num = 0
result = list()
# BFS遍历
while queue:
num = list()
# 按层进行遍历,保证当前处理的都是同一层的节点
for _ in range(0, len(queue)):
node = queue.pop(0)
num.append(node.val)
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
result.append(num)
return result
2. DFS解题思路:
使用反常思路的深度遍历在面试时更具有特点,这题的深度遍历主要要注意深度的记录,在递归调用时要将深度也记录在里边
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def dsf(self, root: TreeNode, level: int, result: list):
if len(result) <= level:
result.append([])
result[level].append(root.val)
if root.left:
self.dsf(root.left, level + 1, result)
if root.right:
self.dsf(root.right, level + 1, result)
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root: return []
result = list()
self.dsf(root, 0, result )
return result