算法刷题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
        

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

相关推荐
timeDifference₇6 小时前
Python Vibe Coding实操实验报告
开发语言·jvm·python
geovindu7 小时前
python:DecisionTree
开发语言·后端·python·算法
怒放的生命19918 小时前
代码知识库 RAG 问答系统 —— 从 0 到 1 实现教程
python·状态模式·fastapi·全栈开发·ai agent应用开发
geovindu8 小时前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
fengkai45459 小时前
Python运维
运维·python·监控·psutil·ipy
Fancy.7619 小时前
:Python条件与循环语句学习总结
python
AllData公司负责人11 小时前
实战二:AllData大模型与AI数据底座-数据传输平台-DBSyncer,搭建 Http 接口同步至 Doris,API 业务数据自动拉取入数仓
大数据·数据库·数据仓库·人工智能·算法·http·doris
Wellijohn11 小时前
Python 容器选型实测:list.insert(0) 慢 925 倍,in 慢 6000 倍
python
新*11 小时前
标题全变成一级?靠编号规律找回章节边界
python·正则表达式·pdf解析·文本处理