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

相关推荐
月光船幽幽2 小时前
检测用户意图复杂性的关键方法
人工智能·python
鹿角片ljp4 小时前
LeetCode 236. 二叉树的最近公共祖先|递归后序
算法
luj_17685 小时前
大律师考核应重能力与科技素养
c语言·开发语言·c++·经验分享·算法
无定义_5 小时前
Floyd——Warshall
算法
刃神太酷啦5 小时前
Linux 系统 MySQL 完整安装配置教程:从卸载 MariaDB 到优化 my.cnf----《Hello MySQL!》(1)
android·linux·c语言·c++·mysql·leetcode·mariadb
威联通网络存储5 小时前
TS-h3087XU-RP 汽车零部件质检追溯部署
python·汽车
你驴我5 小时前
WhatsApp 多账号场景下的会话归档与历史消息检索优化实践
后端·python
IT毕设实战小研5 小时前
基于安卓的空气质量查询系统
android·大数据·vue.js·爬虫·python·django·课程设计
带多刺的玫瑰6 小时前
Leecode#9刷题之回文数
数据结构·算法
harmful_sheep6 小时前
java group by常见用法
java·开发语言·python