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

相关推荐
阳明山水39 分钟前
TimesFM与Moirai MoE零样本预测解析
人工智能·深度学习·算法·机器学习·架构
2501_9419820540 分钟前
企业微信二次开发:如何用 Python 搭建通用的 Webhook 实时消息接收
开发语言·python·企业微信
在世修行41 分钟前
第24篇:PyInstaller打包实战 — 从Python脚本到Windows EXE
人工智能·python·pyinstaller
铅笔侠_小龙虾1 小时前
Rust 学习(2)-变量、常量与 shadowing
学习·算法·rust
AI科技星1 小时前
基于全域数学公理体系的三元极值题最简求解法【乖乖数学】
线性代数·算法·游戏·决策树·机器学习·乖乖数学·全域数学
华研前沿标杆游学1 小时前
2026年制造企业标杆参访实操指南:3步选对适配参访路线
python
Wang ruoxi1 小时前
Pygame 小游戏——一笔画挑战
python·pygame
大鱼>2 小时前
宠物异常行为预警系统:边缘计算与实时检测
人工智能·深度学习·算法·iot·宠物
萧青山2 小时前
AI阅读增强套件:用苏格拉底诘问+对抗性阅读+知识图谱构建深度阅读技能套件(Python实现)
人工智能·python·知识图谱·ai阅读增强
Java面试题总结2 小时前
Python,单引号和双引号有何区别
开发语言·python