Problem: 102. 二叉树的层序遍历
思路
层序遍历,把同一层的节点的值放在同一个列表中
复杂度
时间复杂度: O ( n ) O(n) O(n) n个节点
空间复杂度: O ( n ) O(n) O(n) 列表和队列
Code
# 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: Optional[TreeNode]) -> List[List[int]]:
def bfs(node):
ls = []
if not node: return ls
q = collections.deque([node])
while q:
tem = [] # 存储每一层节点的值
for _ in range(len(q)):
cur_node = q.popleft() # O(1) python list的pop(0)时间复杂度是O(n)
tem.append(cur_node.val)
if cur_node.left: q.append(cur_node.left)
if cur_node.right: q.append(cur_node.right)
ls.append(tem)
return ls
return bfs(root)
281

被折叠的 条评论
为什么被折叠?



