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

相关推荐
随意起个昵称几秒前
【二分】洛谷P2920,P2985做题小记
c++·算法
二川bro3 分钟前
数据可视化进阶:Python动态图表制作实战
开发语言·python·信息可视化
没书读了6 分钟前
计算机组成原理-考前记忆清单
线性代数·算法
青青子衿_2118 分钟前
TikTok爬取——视频、元数据、一级评论
爬虫·python·selenium
Hcoco_me34 分钟前
大模型面试题5:矩阵(M*M)特征值分解的步骤
算法·机器学习·矩阵
忘却的旋律dw1 小时前
使用LLM模型的tokenizer报错AttributeError: ‘dict‘ object has no attribute ‘model_type‘
人工智能·pytorch·python
20岁30年经验的码农1 小时前
Java RabbitMQ 实战指南
java·开发语言·python
非著名架构师1 小时前
极端天气下的供应链韧性:制造企业如何构建气象风险防御体系
大数据·人工智能·算法·制造·疾风气象大模型·风光功率预测
星轨初途1 小时前
数据结构排序算法详解(2)——选择排序(附动图)
c语言·数据结构·经验分享·笔记·b树·算法·排序算法
kaikaile19952 小时前
基于 MATLAB 的室内三维定位
算法