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

相关推荐
Navigator_Z4 小时前
LeetCode //C - 1089. Duplicate Zeros
c语言·算法·leetcode
Unbelievabletobe4 小时前
解决了股票api接口盘后数据更新慢的问题
大数据·开发语言·python
lpd_lt6 小时前
AI Coding的常用Prompt技巧
python·ai·ai编程
小江的记录本6 小时前
【JVM虚拟机】堆内存分代模型:年轻代(Eden+Survivor)、老年代、元空间Metaspace(附《思维导图》+《面试高频考点清单》)
java·前端·jvm·后端·python·spring·面试
在繁华处6 小时前
Java从零到熟练(三):流程控制
java·开发语言·python
asdzx676 小时前
使用 Python 快速提取 PDF 中的表格
python·pdf
无情的西瓜皮7 小时前
MCP协议实战:用Python从零搭建一个AI Agent工具服务器(保姆级教程)
服务器·人工智能·python·mcp
云泽8087 小时前
C++ 可调用对象通关指南:深度解析 Lambda 表达式、function 包装器与 bind 绑定器
开发语言·c++·算法
wlsh157 小时前
Go 迭代器
算法
岁月宁静7 小时前
驾驭 AI 这匹野马:深入解析智能体 Harness 工程
vue.js·python