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

题目链接

描述

思路:

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

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

利用队列长度 记录当前层有多少个节点,每次从队列里取一个节点就size-1,当size0时,即为该层的最后一个节点,然后更新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
        

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

相关推荐
2301_764441332 小时前
LISA时空跃迁分析,地理时空分析
数据结构·python·算法
东北洗浴王子讲AI2 小时前
GPT-5.4辅助算法设计与优化:从理论到实践的系统方法
人工智能·gpt·算法·chatgpt
Billlly3 小时前
ABC 453 个人题解
算法·题解·atcoder
玉树临风ives3 小时前
atcoder ABC 452 题解
数据结构·算法
chushiyunen3 小时前
python rest请求、requests
开发语言·python
cTz6FE7gA3 小时前
Python异步编程:从协程到Asyncio的底层揭秘
python
feifeigo1233 小时前
基于马尔可夫随机场模型的SAR图像变化检测源码实现
算法
baidu_huihui3 小时前
在 CentOS 9 上安装 pip(Python 的包管理工具)
开发语言·python·pip
南 阳3 小时前
Python从入门到精通day63
开发语言·python
lbb 小魔仙3 小时前
Python_RAG知识库问答系统实战指南
开发语言·python