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

相关推荐
8Qi85 小时前
回文子串(Palindromic Substrings)—— 题解
算法·leetcode·职场和发展·动态规划
珺毅同学8 小时前
YOLO生成预测json标签迁移问题
python·yolo·json
骑士雄师8 小时前
18.4 长期记忆可修改版
python
~小先生~8 小时前
Python从入门到放弃(一)
开发语言·python
天佑木枫9 小时前
第2天:变量与数据类型 —— 让程序记住信息
python
小宋加油啊9 小时前
机械臂抓取物体 PVN3D算法调研学习
学习·算法·3d
lqqjuly9 小时前
前沿算法深度解析(一)
算法
Dust-Chasing10 小时前
Claude Code源码剖析 - Claude Code 上下文压缩机制
人工智能·python·ai
小欣加油10 小时前
leetcode1926 迷宫中离入口最近的出口
数据结构·c++·算法·leetcode·职场和发展