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

相关推荐
写的都是BUG41 分钟前
APK 里的钥匙,一直就放在门口:聊聊加固真正该做什么
前端·算法
用户11481867894841 小时前
水印的实现方式逻辑
前端·python
贾公子1 小时前
从单条内容到账号维度——AIGC 风险评分的工程实现
后端·python
地平线开发者1 小时前
CLIP 的零样本分类:一组文本如何变成图像分类器?
算法
京东云开发者2 小时前
从“会生成”到“能生产”:萤火虫 AIGC 平台的 AI Infra 实践
算法·aigc·产品
youshi66682 小时前
PID——算法改进
算法
文丑颜不良啊2 小时前
LeetCode1861~1880题目解析
java·leetcode
文丑颜不良啊3 小时前
LeetCode1921~1940题目解析
java·leetcode
木头左3 小时前
【Python】不点浏览器发博客:逆向 CSDN 创作中心接口做 md-publish 技能
python·自动化·api
Tt有了t3 小时前
设计模式速查
java·python·设计模式