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]]:
queue = collections.deque()
res = []
queue.append(root)
while queue:
tmp = []
n = len(queue)
for _ in range(n):
cur = queue.popleft()
if not cur:
continue
tmp.append(cur.val)
queue.append(cur.left)
queue.append(cur.right)
if tmp:
res.append(tmp)
return res
觉得DFS没有BFS好理解
Thank 负雪明烛, again.