[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记录层次遍历的结果(见[LeetCode]102.二叉树的层序遍历(python)-CSDN博客),然后用result1记录每一层的最后一个数字。

相关推荐
mit6.82423 分钟前
Xai架构
算法
WBluuue34 分钟前
Codeforces 1078 Div2(ABCDEF1)
c++·算法
geovindu37 分钟前
python: Memento Pattern
开发语言·python·设计模式·备忘录模式
寻星探路1 小时前
【JVM 终极通关指南】万字长文从底层到实战全维度深度拆解 Java 虚拟机
java·开发语言·jvm·人工智能·python·算法·ai
lbb 小魔仙1 小时前
【Java】Java 实战项目:手把手教你写一个电商订单系统
android·java·python
岱宗夫up1 小时前
FastAPI入门(上篇):快速构建高性能Python Web API
开发语言·前端·python·fastapi
Dxy12393102161 小时前
中文乱码恢复方案
开发语言·python
田里的水稻1 小时前
FA_融合和滤波(FF)-联邦滤波(FKF)
人工智能·算法·数学建模·机器人·自动驾驶
紫陌涵光2 小时前
112. 路径总和
java·前端·算法
回敲代码的猴子2 小时前
2月8日上机
开发语言·c++·算法