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

相关推荐
gf13211115 分钟前
python_调用远程服务器上的openclaw
服务器·python·php
lbb 小魔仙7 分钟前
Jupyter Notebook / Lab 深度配置指南:插件 + 内核 + 远程访问 + 容器化部署
ide·python·jupyter
2601_9623004710 分钟前
python是跨平台的吗
python·开源·跨平台·面向对象·
qq_5085760913 分钟前
人性机器人部分 算法
算法·机器人
2401_8445829515 分钟前
软件架构设计与持续重构:模块化开发实战建
python
Polevne19 分钟前
C# GRPC 一元与双向流
linux·算法·c#
huang57914722 分钟前
复杂网络中的最短路径搜索算法性能分析3
算法
找方案26 分钟前
AI+气象预报:华为盘古大模型如何让天气预报精准到街区
人工智能·算法·机器学习
东莞市云毅网络有限公司38 分钟前
用 SQLite FTS5 给企业知识库做问答检索原型:中文二元切分与 BM25 排序
python·sqlite·自动化运维·geo·数据监测
承渊政道41 分钟前
PR-Agent鸿蒙PC适配全记录:从Python服务端代理到ArkTS原生评审客户端
python·华为·代理模式·agent·harmonyos·pc端