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
相关推荐
Huangjin007_11 小时前
【C++ STL篇(九)】map容器——零基础入门与核心用法精讲
开发语言·c++·算法
数智工坊11 小时前
【SigLIP论文阅读】:重新定义视觉-语言预训练的损失函数——VLA模型的“语言理解“基石
论文阅读·人工智能·算法·计算机视觉·语言模型
khalil102012 小时前
代码随想录算法训练营Day-53 图论01 | 110.字符串接龙、105.有向图的完全可达性、106.岛屿的周长
算法
IronMurphy12 小时前
【算法四十六】300. 最长递增子序列
算法
罗超驿12 小时前
15.面试高频考点:MySQL索引底层原理与实战要点全梳理
mysql·面试·职场和发展
碧海银沙音频科技研究院12 小时前
高通QCC3084-QCC518X蓝牙耳机项目
人工智能·深度学习·算法
兩尛12 小时前
compare_exchange_weak 的用法
算法
数智工坊12 小时前
面向具身操作的视觉-语言-动作模型:让机器人真正理解并执行人类指令
论文阅读·人工智能·算法·机器人
代码不停12 小时前
记忆化搜索题目练习
java·算法
闻缺陷则喜何志丹12 小时前
【C++动态规划】B3734 [信息与未来 2017] 加强版密码锁|普及+
c++·算法·动态规划·洛谷