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

相关推荐
Python私教1 分钟前
Django 接入 MCP 实战:让 AI 安全调用数据库和业务接口
人工智能·python·django
Python私教6 分钟前
Django 搭建 AI 本地知识库:文档上传、向量检索与智能问答
人工智能·python·django
luj_176829 分钟前
星火科技助力边远地区防病攻坚
c语言·开发语言·c++·经验分享·算法
always_TT36 分钟前
【Python 日志记录:logging 模块入门】
开发语言·python·php
lipku3 小时前
数字人直播开源项目LiveStream
python·开源·数字人·数字人直播
geats人山人海3 小时前
数据结构第六章c语言 树的存储下二叉树的概念和存储
c语言·数据结构·算法
阿童木写作3 小时前
Python实现亚马逊商品图批量智能抠图教程
人工智能·python
axinawang4 小时前
第24课:while循环的应用
python
三亚兴嘉装饰4 小时前
三亚服装店装修
python
小柯南敲键盘4 小时前
速卖通AI图片翻译API集成实战
人工智能·python