【力扣100】102.二叉树的层序遍历

添加链接描述

# 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 result
        q=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-=1
            result.append(mylist)
        return result

思路:

  1. 非常经典的二叉树层序遍历
  2. 使用队列,因为它的先进先出性质
  3. 注意一个点:在向queue中添加元素时,需要判断这个元素十分存在

你可能感兴趣的:(leetcode,算法)