python-leetcode-从中序与后序遍历序列构造二叉树

106. 从中序与后序遍历序列构造二叉树 - 力扣(LeetCode)

python 复制代码
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
        if not inorder or not postorder:  # 如果任一遍历为空,返回 None
            return None
        
        # 根节点是后序遍历的最后一个元素
        root_val = postorder.pop()
        root = TreeNode(root_val)
        
        # 找到根节点在中序遍历中的位置
        root_index = inorder.index(root_val)
        
        # 划分右子树和左子树(注意:先处理右子树,因为后序遍历是左-右-根)
        right_inorder = inorder[root_index + 1:]
        left_inorder = inorder[:root_index]
        
        # 递归构建右子树和左子树
        root.right = self.buildTree(right_inorder, postorder)
        root.left = self.buildTree(left_inorder, postorder)
        
        return root
相关推荐
圣保罗的大教堂32 分钟前
leetcode 3727. 最大交替平方和 中等
leetcode
倚楼听风语1 小时前
Kotlin 协程与 suspend 原理详解
java·算法·kotlin
Xin7701 小时前
LeetCode 200. 岛屿数量(DFS 深度优先遍历法)
leetcode
程序员清风1 小时前
双指针与滑动窗口:高效处理连续区间
开发语言·算法
代钦塔拉1 小时前
【C++/Qt 进阶】设计模式系列(2):工厂模式——从游戏角色到披萨店
c++·算法·设计模式
思茂信息1 小时前
电磁仿真学涉及哪些算法?
人工智能·算法·数学建模·matlab·emc·电磁仿真·仿真辐射
糖果豆豆2 小时前
让 AI 自查三遍,它只会把错的说得更像对的——检查的人和被检查的,是同一个
算法·架构
总裁余(余登武)3 小时前
K-means算法改进(Python版)
python·算法·kmeans
灯澜忆梦3 小时前
【面向对象编程c++】| 指针与自定义数据类型
开发语言·c++·算法
xxwl5854 小时前
区域赛算法模版第八章---贪心(Greedy)
c++·笔记·学习·算法