题目 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]]:
res = [] # 最终结果
if root is None:
return res
queue = [] # 队列
queue.append(root)
while queue:
queue_size = len(queue) # 记录每一层的元素个数
temp = [] # 存放每一层的元素
for i in range(queue_size):
cur_node = queue.pop(0) # 记录当前队列弹出的节点
temp.append(cur_node.val)
if cur_node.left is not None:
queue.append(cur_node.left)
if cur_node.right is not None:
queue.append(cur_node.right)
res.append(temp)
return res
标签:node,遍历,cur,self,append,queue,right,二叉树,四种
From: https://www.cnblogs.com/edkong/p/16823081.html