一、学习视频
【二叉树的层序遍历【基础算法精讲 13】】 https://www.bilibili.com/video/BV1hG4y1277i/?share_source=copy_web\&vd_source=dc0e55cfae3b304619670a78444fd795
二、跟练代码
1.102. 二叉树的层序遍历
python
# 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]]:
# 双列表
if not root:
return []
# 现在节点、子节点、现在节点值列表
cur, ans = [root], []
while cur:
nxt, val = [], []
# 遍历现在节点列表
for x in cur:
val.append(x.val)
if x.left:
nxt.append(x.left)
if x.right:
nxt.append(x.right)
ans.append(val)
cur = nxt
return ans
(未完待续)