题目:(二叉树的层序遍历)给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
示例 1:
输入:root = [3,9,20,null,null,15,7] 输出:[[3],[9,20],[15,7]] 示例 2:
输入:root = [1] 输出:[[1]]
示例 3:输入:root = [] 输出:[]
提示:
树中节点数目在范围 [0, 2000] 内
-1000 <= Node.val <= 1000
程序说明:
先判断根节点是否为空,若是则直接返回空列表。若不为空,则将root存入列表ans中,创建两个列表,使用for循环ans中的数,将它的值存入创建的其中一个列表current中,再判断它的左右孩子节点是否存在,若存在则存入另一个列表next_root中,跳出for循环以后,将current存入一个新列表res中,接着将next_root赋给ans,接着对ans重复以上操作。
全部代码:
# 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: TreeNode) -> List[List[int]]:
if root == None:
return []
res=[]
ans = [root]
while ans:
current = []
next_root = []
for node in ans:
current.append(node.val)
if node.left:
next_root.append(node.left)
if node.right:
next_root.append(node.right)
res.append(current)
ans = next_root
return res
题目来源:力扣(LeetCode)