解题思路

在while循环中遍历每一层(curr_node_list)
将curr_node_list中每一个元素的val存入该层的值的list(temp_val_list)
将curr_node_list中每一个元素的left和right顺次存入该层的子结点的list(temp_son_list)
层遍历完结后,更新curr_node_list
while退出条件:curr_node_list为空

原题链接
欢送在我的博客轻松摸索更多思路

代码

class Solution:    def levelOrder(self, root: TreeNode) -> List[List[int]]:        result=[]        curr_node_list=[]        curr_node_list.append(root)        while(curr_node_list):            temp_son_list=[]            temp_val_list=[]            for father in curr_node_list:                if father:                    temp_val_list.append(father.val)                    try:                        temp_son_list.append(father.left)                    except:                        pass                    try:                        temp_son_list.append(father.right)                    except:                        pass            if(temp_val_list):                result.append(temp_val_list)            curr_node_list=temp_son_list        return result