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

相关推荐
benchmark_cc6 分钟前
个人量化系统搭建:如何利用 QuantDash 实现 A 股日 K 线前复权数据的高效获取与质量校验?
python·数据分析·pandas·量化交易·股票数据·quantdash
hhb_61813 分钟前
Python异步队列实战:高效处理耗时任务
开发语言·python
2601_9628857217 分钟前
一个接口取 A 股+美股+港股:多市场数据方案对比
python
SEO_juper24 分钟前
Node.js 全站死链检测工具:从 sitemap 出发一次找全 404
开发语言·人工智能·python·node.js·seo·外贸独立站
ljt272496066128 分钟前
Python笔记(九)--asyncio
笔记·python
吞下星星的少年·-·28 分钟前
牛客周赛 119B题(贪心)
算法·贪心
老孟说禅37 分钟前
自动化测试实战(二)
python
NEFU_Jyj38 分钟前
牛客周赛R166(max型瓶颈最短路,前后缀DP合并)
算法·深度优先
2601_9679873742 分钟前
你们都用Python实现了哪些自动化办公?
python·excel·自动化办公·1024程序员节·学习资料·跨平台操作
wflynn43 分钟前
GitHub 今日推荐|Snapintosh:用 ARM EL2 监控器骗过内核,让骁龙芯片笔记本跑 macOS
python·开源·github