[LeetCode]199.二叉树的右视图(python)

1.代码

python 复制代码
# 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 rightSideView(self, root: Optional[TreeNode]) -> List[int]:
        result1: List[int] = []
        i = 0
        queue = deque()
        result : List[List[int]] = []
        if root==None:
            return result
        queue.append(root)
        while(queue):
            length = len(queue)
            result.append([])
            for j in range (length):
                item = queue.popleft()
                if item.left:
                    queue.append(item.left)
                if item.right:
                    queue.append(item.right)
                result[i].append(item.val)
            i=i+1
        for item in result:
            result1.append(item[len(item)-1])
        return result1

2.思路

首先用result记录层次遍历的结果(见LeetCode102.二叉树的层序遍历(python)-CSDN博客),然后用result1记录每一层的最后一个数字。

相关推荐
战族狼魂1 分钟前
高频面试题精选:分治与AI Agent架构
人工智能·算法·大模型·大语言模型
weixin_408099675 分钟前
2026 图片去水印 API 接口完全指南:一键去除图片水印(附 Python/Java/PHP/C# 示例)
java·python·php·图片处理·api调用·图片去水印·石榴智能
李剑一7 分钟前
你用过网易的将军令嘛?它底层实现账号保护的原理相当简单粗暴
算法
Scott9999HH13 分钟前
告别流量波动玄学!从法拉第电磁定律到底层 C/C++ 流量累积算法,深度解密工业级电磁流量计选型与开发
c语言·c++·算法
去码头整点薯条ing41 分钟前
某当网登录滑块【协议+OCR】
爬虫·python·ocr
香辣牛肉饭1 小时前
【算法】动态规划 最长公共子序列(LCS)
经验分享·笔记·算法·动态规划
赶紧写完去睡觉1 小时前
Anaconda 创建虚拟环境与使用
python·pycharm·conda
迷途呀1 小时前
Python:函数中的参数类型
开发语言·笔记·python·langchain·nlp
你驴我2 小时前
WhatsApp 多账号下消息已读回执的实时聚合与推送实践
后端·python