• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

LeetCode-102-Binary-Tree-Level-Order-Traversal

python 搞代码 3年前 (2022-03-30) 19次浏览 已收录 0个评论
文章目录[隐藏]

解题思路

在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

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:LeetCode-102-Binary-Tree-Level-Order-Traversal
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址