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

相关推荐
随便发挥8 小时前
Leetcode 剑指 Offer II 186. 文物朝代判断
leetcode
6Hzlia8 小时前
【Classic 150 刷题计划】 LeetCode 205. 同构字符串 | C++ 双向绑定与哈希表映射
c++·算法·leetcode
Y幽谷客14 小时前
Python加载本地大模型(Qwen3.5 8B)
python·大模型
伞伞悦读15 小时前
【第36期】Python 目录与路径详解:pathlib、文件遍历、创建、复制、移动和删除风险
开发语言·python
有点。15 小时前
C++03阶段练习(练习题)
数据结构·算法·图论
线上放牧人15 小时前
Windows删除图标缓存
windows·python·pyqt
qq_54702617915 小时前
Python 变量和简单数据类型
python
周末也要写八哥16 小时前
经典算法实例:游戏中弱角色的数量(二)
算法
是Yu欸16 小时前
鸿蒙PC移植:2048 从网页小游戏到 AI 桌面应用
大数据·人工智能·算法·数据挖掘·openharmony·codex
鹿角片ljp16 小时前
KV Cache 解析
java·算法