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

相关推荐
m0_7066532317 分钟前
C++编译期数组操作
开发语言·c++·算法
故事和你9127 分钟前
sdut-Java面向对象-06 继承和多态、抽象类和接口(函数题:10-18题)
java·开发语言·算法·面向对象·基础语法·继承和多态·抽象类和接口
Imm77734 分钟前
中国知名的车膜品牌推荐几家
人工智能·python
qq_4232339039 分钟前
C++与Python混合编程实战
开发语言·c++·算法
tudficdew40 分钟前
实战:用Python分析某电商销售数据
jvm·数据库·python
TracyCoder1231 小时前
LeetCode Hot100(19/100)——206. 反转链表
算法·leetcode
m0_715575341 小时前
分布式任务调度系统
开发语言·c++·算法
sjjhd6521 小时前
Python日志记录(Logging)最佳实践
jvm·数据库·python
naruto_lnq1 小时前
泛型编程与STL设计思想
开发语言·c++·算法