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
相关推荐
文丑颜不良啊9 小时前
LeetCode3101~3120题目解析
java·leetcode
kyle~13 小时前
模型预测控制(MPC)
算法·机器人·控制·传感器
牢姐与蒯14 小时前
cpp算法之哈希
c++·算法·哈希算法
开开心心就好15 小时前
两张表格数据对比工具,不用写函数也能查
算法·spring·智能手机·pdf·电脑·intellij-idea·音视频
电科_银尘16 小时前
【大模型算法与工程 02】线性回归与逻辑回归:从损失函数到决策边界
算法·逻辑回归·线性回归
玄昌盛不会编程17 小时前
LeetCode——2243. 计算字符串的数字和
java·算法·leetcode
文丑颜不良啊17 小时前
LeetCode3061~3080题目解析
java·leetcode
电科_银尘19 小时前
【大模型算法与工程 01】机器学习的问题定义:监督、无监督、自监督与强化学习
人工智能·算法·机器学习
文丑颜不良啊19 小时前
LeetCode3081~3100题目解析
java·leetcode
电科_银尘20 小时前
【大模型算法与工程 05】分类、回归与排序指标:怎样评价一个模型
算法·分类·回归