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

相关推荐
鱼香rose__5 分钟前
2024icpc南京站
算法
LQS20205 分钟前
基于Python实现一个庆祝中秋节的小程序
开发语言·python·小程序
夜半罟霖6 分钟前
算法手撕面经系列(1)--手撕多头注意力机制
python·深度学习·算法
重生成为码农‍10 分钟前
Java高级Day40-QQ项目全代码
java·开发语言·算法
fish_study_csdn25 分钟前
使用Django 搭建自动化平台
python·django·自动化
城府阳光35 分钟前
第 1 0 章OpenCV
人工智能·python·神经网络·机器学习
小冉在学习43 分钟前
leetcode刷题day13|二叉树Part01(递归遍历、迭代遍历、统一迭代、层序遍历)
算法·leetcode·职场和发展
我就想睡到自然醒43 分钟前
《UniVS: Unified and Universal Video Segmentation with Prompts as Queries》要点提炼
人工智能·算法·机器学习
A.A呐1 小时前
LeetCode 692.前K个高频单词
c++·算法·leetcode