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

相关推荐
Ivanqhz9 分钟前
MoE 原理、TC/EC 路由、LSH-MoE 与负载均衡浅析
运维·网络·人工智能·深度学习·算法·机器学习·负载均衡
Sarvartha12 分钟前
栈的四则运算、栈的递归应用
数据结构·算法
stolentime18 分钟前
CF2277E Tree Guessing题解
c++·算法·贪心算法·交互·ad-hoc
逐光者93334 分钟前
杨氏模量:从定义到工程应用
算法
quantdash_cc41 分钟前
如何检查滚动收益率计算中的窗口长度不足?——从数学定义到 Pandas 实现
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
砚底藏山河1 小时前
python量化:实时行情WebSocket断线重连状态机
java·python·websocket·金融
CodeGL1 小时前
16、Python Web开发
开发语言·前端·python
加点盐1 小时前
别再用 configparser 了:给本地配置加上加密、校验和版本迁移
python
小嘉丶学长1 小时前
Day08 · 字符串(二)
服务器·开发语言·python·学习·1024程序员节
BD_Marathon1 小时前
【Python】列表推导式
python