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 分钟前
B3842 [GESP202306 三级] 春游 题解
数据结构·c++·算法·题解
atunet34 分钟前
树状结构在查询优化中的作用与实现细节7
算法
徐凤年_1 小时前
rog_map参数理解
算法
春日见1 小时前
算法与数据结构----哈希表
数据结构·人工智能·算法·机器学习·自动驾驶·哈希算法·散列表
叩码以求索2 小时前
统计按位或能得到最大值的子集数目(一)
数据结构·算法
tachibana22 小时前
hot100 数组中的第K个最大元素(215)
java·数据结构·算法·leetcode
txzrxz2 小时前
单调队列讲解
数据结构·c++·算法·单调队列
不会就选b3 小时前
算法日常・每日刷题--<快排>4
算法
Keven_113 小时前
算法札记:树状数组的用途
数据结构·算法
用户677437175813 小时前
C++函数参数传递方式详解:string、string&、const string、const string&该怎么选?
算法