添加链接描述
# 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]]:result=[]if not root:return resultq=collections.deque()q.append(root)while q:size=len(q)mylist=[]while size:cur=q.popleft()mylist.append(cur.val)if cur.left:q.append(cur.left)if cur.right:q.append(cur.right)size-=1result.append(mylist)return result
思路:
- 非常经典的二叉树层序遍历
- 使用队列,因为它的先进先出性质
- 注意一个点:在向queue中添加元素时,需要判断这个元素十分存在