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

相关推荐
godspeed_lucip15 小时前
LLM和Agent——专题5: LLM Ops 入门(2)
人工智能·python
技术钱15 小时前
RAG 开发 6 个阶段优化策略分析
python
-To be number.wan15 小时前
算法日记 | STL-MAP
c++·算法
cjp56015 小时前
015. UG 二次开发,拉伸草图生成实体类,高级草图类封装
算法
QFIUNE15 小时前
使用 MMseqs2 计算多个 DTI 数据集的蛋白序列相似度
linux·python·ubuntu
念恒1230615 小时前
Python 函数完全指南:定义与调用
开发语言·python
大数据魔法师15 小时前
Streamlit(十二)- API 参考文档(五)- 输入组件
python·web
涛声依旧-底层原理研究所15 小时前
Node.js在高并发低延迟场景中的优势
java·人工智能·python·node.js
Eric 辰东15 小时前
【C 语言程序的编译和链接】详解编译链接过程
c语言·笔记·算法·学习方法
迈巴赫车主15 小时前
蓝桥杯21247弹跳鞋java
java·开发语言·数据结构·算法·职场和发展·蓝桥杯