算法刷题Day18: BM41 输出二叉树的右视图

题目链接

描述

思路:

递归构造二叉树在Day15有讲到。复习一下,就是使用递归构建左右子树。将中序和前序一分为二。

接下来是找出每一层的最右边的节点,可以利用队列+层次遍历。

利用队列长度 记录当前层有多少个节点,每次从队列里取一个节点就size-1,当size为0时,即为该层的最后一个节点,然后更新size为队列长度。

代码:

python 复制代码
import queue
def constructTree(preOrder,vinOrder):
    # 递归退出条件
    if len(preOrder) == 0:
        return None
    # 根节点
    root_val = preOrder[0]
    root = TreeNode(root_val)
    index = vinOrder.index(root_val)
    
    leftnode = constructTree(preOrder[1:index+1], vinOrder[:index])
    rightnode = constructTree(preOrder[index+1:],vinOrder[index+1:])
    root.left = leftnode
    root.right = rightnode
    return root

class Solution:
    def solve(self , preOrder: List[int], inOrder: List[int]) -> List[int]:
        # write code here
        # 根据前中序,构建一棵树
        # 基础:找出每一层的最右边的节点
        root = constructTree(preOrder, inOrder)
        result = []
        q = queue.Queue()
        q.put(root)
        # 记录每一层的size
        size = 1
        while not q.empty():
            node = q.get()
            if node.left:
                q.put(node.left)
            if node.right:
                q.put(node.right)
            size -= 1
            if size == 0:
                # 最后一个节点
                size = q.qsize()
                result.append(node.val)
        return result
        

还完债了,回家就刀片嗓有点难受啊,以后再也不吃啫啫煲了,好上火。

相关推荐
阿维的博客日记6 分钟前
大白话解析快排Python
python
doujiaozh23 分钟前
我在 DOS 6.22 上跑通了 Kimi AI:一场跨越 40 年的硬核接力
python
凛铄linshuo36 分钟前
分析业务流程什么时候适合断言?
python·pytest
倚楼听风语1 小时前
Kotlin 协程与 suspend 原理详解
java·算法·kotlin
程序员清风1 小时前
双指针与滑动窗口:高效处理连续区间
开发语言·算法
import_random1 小时前
[python]IDE可以自动检测venv工具创建的虚拟环境.venv吗
python
代钦塔拉1 小时前
【C++/Qt 进阶】设计模式系列(2):工厂模式——从游戏角色到披萨店
c++·算法·设计模式
思茂信息1 小时前
电磁仿真学涉及哪些算法?
人工智能·算法·数学建模·matlab·emc·电磁仿真·仿真辐射
楠风测开1 小时前
Python学习路线:搭好环境,跑通第一个脚本
python
code2cat1 小时前
【随笔】RAG重排怎样挑证据:先扩大候选,再把相关片段排到前面
人工智能·python·大语言模型·rag