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

相关推荐
n***27193 分钟前
JAVA (Springboot) i18n国际化语言配置
java·spring boot·python
心无旁骛~5 分钟前
python多进程multiprocessing——spawn启动方式解析
开发语言·python
@Aurora.9 分钟前
优选算法【专题二:滑动窗口】
算法
家家小迷弟14 分钟前
docker容器内部安装python和numpy的方法
python·docker·numpy
小石头 1008614 分钟前
【Java】String类(超级详细!!!)
java·开发语言·算法
conkl17 分钟前
Python中的鸭子类型:理解动态类型的力量
开发语言·python·动态·鸭子类型·动态类型规划
.柒宇.19 分钟前
力扣hot100---42.接雨水(java版)
java·算法·leetcode
故事挺秃然21 分钟前
Python异步(Asyncio)(一)
服务器·网络·python
youngee1125 分钟前
hot100-41验证二叉搜索树
算法
迈巴赫车主27 分钟前
蓝桥杯20534爆破 java
java·数据结构·算法·职场和发展·蓝桥杯