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

相关推荐
郭老二37 分钟前
【Python】常用模块:xmlrpc
python
名字还没想好☜1 小时前
Python itertools 实战:用 groupby、chain、islice 优雅处理大数据流
linux·windows·python·迭代器·itertools
可编程芯片开发1 小时前
UPFC统一潮流控制器的simulink建模与仿真
算法
威联通网络存储2 小时前
TS-h2490FU在面板制造Array段AOI缺陷画廊中的并联
python·制造
小小仙子2 小时前
矢量网络分析仪如何测试S参数的?
人工智能·算法·机器学习
接针2 小时前
UV 常用命令
python·uv
中微极客3 小时前
降维算法75倍加速:从PCA到稀疏字典学习的工程实践
人工智能·学习·算法
storyseek4 小时前
前缀和实现Kogge-Stone算法
数据结构·算法
无垠的广袤4 小时前
【工业树莓派 CM0 Dev Board】扩展板设计
linux·python·嵌入式硬件·pcb设计·模块化·传感器