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

相关推荐
摇滚侠8 分钟前
《On Java 中文版 基础卷》阅读笔记 对象无处不在 03
java·笔记·python
لا معنى له10 分钟前
World-In-World: World Models in a Closed-Loop World
算法
小小小小钰儿33 分钟前
1.5-Python网络编程
开发语言·网络·python·web安全·计算机·网络安全
keke.shengfengpolang35 分钟前
2026年金融风控岗技术能力拆解:SQL取数、Python建模、评分卡项目,校招面试到底考什
python
kyrie_sakura1 小时前
大模型学习7 -- 深度学习2 -- 张量
python·深度学习
智鸟科技GemeOpen开发者智能设备2 小时前
智能插座二次开发如何接入Home Assistant,从零开始完整工程实现(Python+React)
开发语言·python·物联网·react.js·智能家居
hqyjzsb2 小时前
法律 Prompt 干货:搭建合同审查提示词要包含哪些要素
开发语言·人工智能·python·职场和发展·数据分析·prompt·业界资讯
Andreapiki2 小时前
风险审计校招技术栈拆解:SQL、Python、Power BI在2026届JD中的真实权重
数据库·python·sql
Discipline10292 小时前
尼泊尔河流流量:天气驱动的预测与高流量风险
人工智能·算法