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

相关推荐
kebidaixu27 分钟前
两轮BMS 短路保护策略详解
算法
ai生成式引擎优化技术32 分钟前
从知识连接到智能组织:WSaiOS认知网络的理论框架与系统设计摘要
网络·python·plotly·django·pygame
用户83562907805136 分钟前
使用 Python 保护和取消保护 Excel 工作表和工作簿
后端·python
zwenqiyu1 小时前
非线性字符串数据结构串讲
数据结构·c++·学习·算法
z小猫不吃鱼1 小时前
03 Optimal Brain Surgeon 详解:Hessian 剪枝为什么有效?
算法·机器学习·剪枝
骑士雄师1 小时前
大模型:临时会话
开发语言·python
硕风和炜1 小时前
【LeetCode: 1301. 最大得分的路径数目 + DP】
java·算法·leetcode·动态规划·dp·记忆化搜索
用户99045017780091 小时前
做了一个AI诊断,参考倪海厦中医理论,科学养生
算法
努力中的编程者1 小时前
STL-vector的模拟实现
开发语言·c++·算法·stl·vector
山海云端有限公司2 小时前
实战指南:用豆包图片生成API快速搭建AI绘画能力
python·ai绘画·api调用·图片生成·豆包api