关于python:LeetCode-102-Binary-Tree-Level-Order-Traversal

8次阅读

共计 639 个字符,预计需要花费 2 分钟才能阅读完成。

解题思路

在 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
正文完
 0