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

相关推荐
雪的季节5 小时前
Python基础5-18
开发语言·python
学术小李5 小时前
基于Pytorch,如何用CUDA自己写算子?(一)
人工智能·pytorch·python
QXWZ_IA5 小时前
桥梁数字孪生怎么落地?
人工智能·科技·算法·智能硬件·政务
ShirleyWang0125 小时前
让headlamp控制台能访问
linux·服务器·python·k8s·k3s
Kel5 小时前
输出层与反分词(Output Layer & Detokenization)
人工智能·算法·架构
陕西企来客5 小时前
2026年7月技术好GEO优化方案:算法适配与内容策略
人工智能·算法·机器学习·技术好geo优化
想会飞的蒲公英5 小时前
用 Streamlit 给文本分类模型做一个演示页面
人工智能·python·机器学习
老徐聊GEO5 小时前
亲测有效的AI品牌检测公司案例分享
大数据·人工智能·python
风栖柳白杨6 小时前
【面试】AI算法工程师_空白自测版本
人工智能·算法·面试
华研前沿标杆游学6 小时前
2026年企业对标学习TOP7项目:小米数字化考察上榜
python