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

相关推荐
WL_Aurora几秒前
Python 算法基础篇之什么是算法
python·算法
乐世东方客7 分钟前
Nacos-2.1.0问题-自己记录
开发语言·python
墨染天姬8 分钟前
[AI]DeepSeek-R1的GRPO算法
人工智能·算法·php
D_C_tyu10 分钟前
JavaScript | 数独游戏核心算法实现
javascript·算法·游戏
qiqsevenqiqiqiqi11 分钟前
MT2048三连 暴力→数学推导→O (n) 优化
数据结构·c++·算法
AI技术增长12 分钟前
Pytorch图像去噪实战(二):用UNet解决DnCNN细节丢失问题(结构解析+完整代码+踩坑总结)
人工智能·pytorch·python
码之气三段.18 分钟前
十五届山东ccpc省赛补题(update)
数据结构·c++·算法
dFObBIMmai31 分钟前
CSS如何检测页面浮动元素位置_使用审查工具与clear
jvm·数据库·python
qq_4609784036 分钟前
实现 Svelte 中基于数组索引的 details 元素单开单关交互
jvm·数据库·python
AI科技星1 小时前
ELN 升级:π 级数自动生成器全域数理架构
大数据·人工智能·python·算法·金融