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

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

相关推荐
JieE21218 小时前
LeetCode 101. 对称二叉树|JS 递归 + 迭代双解法,彻底搞懂镜像判断
javascript·算法
金銀銅鐵1 天前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup111 天前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi001 天前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵1 天前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf1 天前
Agent 流程编排
后端·python·agent
copyer_xyf1 天前
Agent RAG
后端·python·agent
copyer_xyf1 天前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf1 天前
Agent 记忆管理
后端·python·agent