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

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

相关推荐
电科_银尘3 小时前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法
郝学胜-神的一滴7 小时前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
秋天的怀念_David7 小时前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
学无止境小袁同学8 小时前
Google ADK 学习指南
python·llm·agent·多agent·google adk·llmagent·agent cli
郝学胜-神的一滴9 小时前
Effective Python 条款35:用类封装替代生成器异常注入
开发语言·人工智能·python·金融·pandas·scikit-learn·matplotlib
LK_079 小时前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
wuyk5559 小时前
Python办公自动化-第02讲-Excel文件认知与四大库选型
开发语言·python·excel
Pniubi10 小时前
力扣21合并两个有序链表
算法·leetcode·职场和发展
AIgorithmGEEK10 小时前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set