[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记录层次遍历的结果(见[LeetCode]102.二叉树的层序遍历(python)-CSDN博客),然后用result1记录每一层的最后一个数字。

相关推荐
qq_18980703几秒前
JavaScript 中高效定位二维数组间不匹配元素的行列索引
jvm·数据库·python
程序员大雄学编程2 分钟前
微积分40. 有理函数的积分法(上)
python·微积分
qq_349317484 分钟前
Python GUI界面如何实现主题美化_引入ttk模块实现原生外观风格
jvm·数据库·python
yuanpan4 分钟前
Python Scrapy 入门教程:从零学会抓取和解析网页数据
java·python·scrapy
Lumos_77711 分钟前
Linux -- 系统调用
linux·运维·算法
forEverPlume12 分钟前
c++如何通过解析二进制包头信息解决Socket传输过程中的粘包问题【详解】
jvm·数据库·python
玉小格19 分钟前
对py作业的一个复盘
开发语言·python
BU摆烂会噶19 分钟前
【LangGraph 持久化】让 AI Agent 拥有“记忆”
数据库·人工智能·python·langchain
一个行走的民25 分钟前
深度剖析 Ceph PG 分裂机制:原理、底层、实操、影响、线上避坑(最全完整版)
ceph·算法
WolfGang00732128 分钟前
代码随想录算法训练营 Day46 | 图论 part04
算法·图论