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

相关推荐
灯澜忆梦10 分钟前
GO_函数_1
算法
言乐631 分钟前
Python实现建造微服务商城后台
开发语言·python·算法·微服务·架构
凉云生烟1 小时前
机器学习 02- KNN算法
人工智能·算法·机器学习
fenglllle1 小时前
chromadb emmbedding 向量检索
人工智能·python·embedding
wabs6661 小时前
关于动态规划【力扣583.两个字符串的删除操作的思考】
算法·leetcode·动态规划
cui_ruicheng1 小时前
Python从入门到实战(六):非序列容器
开发语言·python
可编程芯片开发1 小时前
空气流量和空气压力参数解耦系统simulink建模与仿真
算法
_Doubletful1 小时前
妙用位运算:解构汉明距离至100%(提供分析与多解)
c语言·算法·leetcode
凯瑟琳.奥古斯特1 小时前
力扣1013三等分解法与C++实现
开发语言·c++·算法·leetcode·职场和发展
飞猪~2 小时前
Langchain python版本 LLM 重要函数invoke,ainvoke,stream,astream,batch,abatch
python·langchain·batch