1. BFS使用队列
使用两个队列存储二叉树,主队列循环遍历各层,临时队列对每一层元素遍历,代码如下,res存放层序遍历结果:
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
queue = [root]
res = []
level = 0
while len(queue) > 0:
res.append([])
temp = []
for p in queue:
res[level].append(p.val)
if p.left:
temp.append(p.left)
if p.right:
temp.append(p.right)
queue = temp
level += 1
return res
时间复杂度:O(N) 空间复杂度:O(N)
2. DFS
class Solution:
def dfs(self, root, d, res):
if not root:
return
if len(res) == d:
res.append([])
res[d].append(root.val)
self.dfs(root.left, d+1, res)
self.dfs(root.right, d+1, res)
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
res = []
self.dfs(root, 0, res)
return res
时间复杂度:O(N) 空间复杂度:O(N)
|