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

相关推荐
dazzle1 小时前
机器学习算法原理与实践-入门(十一):基于PyTorch的房价预测实战
pytorch·算法·机器学习
紫金修道7 小时前
【DeepAgent】概述
开发语言·数据库·python
书到用时方恨少!8 小时前
Python multiprocessing 使用指南:突破 GIL 束缚的并行计算利器
开发语言·python·并行·多进程
Warson_L8 小时前
Python 常用内置标准库
python
Warson_L9 小时前
Python 函数的艺术 (Functions)
python
Warson_L9 小时前
Python 流程控制与逻辑
后端·python
long_songs9 小时前
手柄键盘映射器【github链接见文末 】
python·游戏·计算机外设·pygame·软件推荐·手柄映射键盘
必然秃头9 小时前
Python 环境安装及项目构建指南
python
Warson_L9 小时前
Python 四大组合数据类型 (Collection Types)
后端·python
廋到被风吹走9 小时前
【AI】Codex 多语言实测:Python/Java/JS/SQL 效果横评
java·人工智能·python