这个题目比较基础,可以对树的广度优先搜索的模版稍作更改,就可以得到我们的答案了。题目如下:
解答如下:
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: if not root: return [] #跟结点入queue queue = [root] res = [] while queue: res.append([node.val for node in queue]) #存储当前层的孩子节点列表 ll = [] #对当前层的每个节点遍历 for node in queue: #如果左子节点存在,入队列 if node.left: ll.append(node.left) #如果右子节点存在,入队列 if node.right: ll.append(node.right) #后把queue更新成下一层的结点,继续遍历下一层 queue = ll return res
方法二:
class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: if not root: return [] res = [] queue = [root] while queue: tmp = [] for _ in range(len(queue)): node = queue.pop(0) tmp.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) res.append(tmp) return res
对二叉树层序遍历的模版如下:
def BFS(root): if root: res = [] queue = [root] while queue: currentNode = queue.pop(0) res.append(currentNode.val) if currentNode.left: queue.append(currentNode.left) if currentNode.right: queue.append(currentNode.right) return res