头图

解题思路

在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

Uzecode
1 声望0 粉丝

De tout temps les hommes ont cru qu’ils étaient mieux que leurs voisins…Les autres nous sont inférieurs parce qu’on les juge par les critères qu’on s’applique à soi-même.