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

相关推荐
a程序小傲21 分钟前
京东Java面试被问:动态规划的状态压缩和优化技巧
java·开发语言·mysql·算法·adb·postgresql·深度优先
自学不成才36 分钟前
深度复盘:一次flutter应用基于内存取证的黑盒加密破解实录并完善算法推理助手
c++·python·算法·数据挖掘
June`1 小时前
全排列与子集算法精解
算法·leetcode·深度优先
徐先生 @_@|||1 小时前
Palantir Foundry 五层架构模型详解
开发语言·python·深度学习·算法·机器学习·架构
深蓝电商API2 小时前
Scrapy爬虫限速与并发控制最佳实践
爬虫·python·scrapy
Derrick__12 小时前
淘宝MD5爬虫
爬虫·python
薛定谔的猫19822 小时前
llama-index Embedding 落地到 RAG 系统
开发语言·人工智能·python·llama-index
夏鹏今天学习了吗2 小时前
【LeetCode热题100(78/100)】爬楼梯
算法·leetcode·职场和发展
圣保罗的大教堂2 小时前
leetcode 712. 两个字符串的最小ASCII删除和 中等
leetcode