[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记录每一层的最后一个数字。

相关推荐
吃我一窝jio3 小时前
Python与Go线程模型深度对比
java·开发语言·python
文丑颜不良啊3 小时前
LeetCode3041~3060题目解析
java·leetcode
罗西的思考3 小时前
【轻量化复现大模型 / KIMI K3】MTP / EAGLE‑3 模块交互式演示
人工智能·深度学习·算法
zwd20053 小时前
Manim 怎么放大画面的某一部分?
python·动画·可视化·manim·数学动画
屿华AI4 小时前
AUTOSAR 实战-诊断工具 | UDS 0x27 安全访问的配置化实现:种子密钥算法插件化设计
python·测试工具·汽车
RobinDevNotes4 小时前
Claude Code 剪视频,不上传、不要 API Key
人工智能·python·音视频·开发工具·ipython
文丑颜不良啊4 小时前
LeetCode3101~3120题目解析
java·leetcode
如夏倾城6 小时前
VRRP(虚拟路由器冗余协议Virtual Router Redundancy Protocol)
网络·python·网络协议·安全·智能路由器·负载均衡·信息与通信
IvanCodes6 小时前
LangChain(04):Runnable 与 LCEL 的执行与组合机制
python·langchain·agent
特创数字科技6 小时前
纯本地离线运行的文档脱敏工具(技术分享)
前端·驱动开发·python