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

相关推荐
小羊在奋斗12 分钟前
【LeetCode 热题 100】二叉树的最大深度 / 翻转二叉树 / 二叉树的直径 / 验证二叉搜索树
算法·leetcode·职场和发展
墨绿色的摆渡人20 分钟前
pytorch小记(二十一):PyTorch 中的 torch.randn 全面指南
人工智能·pytorch·python
大叔_爱编程23 分钟前
p024基于Django的网上购物系统的设计与实现
python·django·vue·毕业设计·源码·课程设计·网上购物系统
一个天蝎座 白勺 程序猿32 分钟前
Python爬虫(29)Python爬虫高阶:动态页面处理与云原生部署全链路实践(Selenium、Scrapy、K8s)
redis·爬虫·python·selenium·scrapy·云原生·k8s
90后小陈老师32 分钟前
WebXR教学 09 项目7 使用python从0搭建一个简易个人博客
开发语言·python·web
weixin-WNXZ021844 分钟前
闲上淘 自动上货工具运行原理解析
爬虫·python·自动化·软件工程·软件需求
2301_794461571 小时前
力扣-283-移动零
算法·leetcode·职场和发展
编程绿豆侠1 小时前
力扣HOT100之二叉树:98. 验证二叉搜索树
算法·leetcode·职场和发展
正在走向自律1 小时前
Conda 完全指南:从环境管理到工具集成
开发语言·python·conda·numpy·fastapi·pip·开发工具
技术流浪者1 小时前
C/C++实践(十)C语言冒泡排序深度解析:发展历史、技术方法与应用场景
c语言·数据结构·c++·算法·排序算法