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

相关推荐
m0_547486661 分钟前
《Python数据分析与可视化项目教程》全套PPT课件2026
python·数据分析·数据可视化
hqyjzsb3 分钟前
规划工商管理大学成长:搭建四层能力体系,重视高阶的 AI 能力建设
开发语言·人工智能·python·microsoft·职场和发展·数据挖掘·业界资讯
AgentMaster8 分钟前
开源智能客服系统技术对比:从架构设计到生产部署的实战指南
大数据·人工智能·算法
我不会起名字3228 分钟前
一天一道算法题(35):电话号码的字母组合
java·数据结构·后端·python·leetcode·go·回溯
冯一川8 分钟前
DeepSeek在Windows系统上部署
windows·python
小叶肥辉12 分钟前
LangChain链和LangGraph图的学习笔记【六】——提示语模板(3)——Few-Shot Prompting(少样本提示) 模板类
笔记·python·学习·langchain·prompt·aigc
for_ever_love__22 分钟前
爬虫项目: 获取高分电影的数据总结
开发语言·python·学习
文人sec24 分钟前
MYSQL:insert...select:为什么锁源表的所有行和间隙?怎么最快地复制一张表?
数据库·python·mysql
weixin_3077791327 分钟前
C++代码实现MATLAB中的ode23t函数功能
开发语言·c++·算法·matlab
萧西待水44 分钟前
奥赛一本通 1451 棋盘游戏
算法·宽度优先