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
相关推荐
YunchengLi21 分钟前
【计算机图形学中的四元数】2/2 Quaternions for Computer Graphics
人工智能·算法·机器学习
CUC-MenG1 小时前
Codeforces Round 1079 (Div. 2)A,B,C,D,E1,E2,F个人题解
c语言·开发语言·数学·算法
666HZ6661 小时前
数据结构4.0 串
c语言·数据结构·算法
weixin_421585011 小时前
常微分方程
算法
文艺倾年2 小时前
【免训练&测试时扩展】通过任务算术转移思维链能力
人工智能·分布式·算法
curry____3032 小时前
dfs全排列和全组合问题
算法·深度优先
想做功的洛伦兹力12 小时前
2026/2/12日打卡
开发语言·c++·算法
大模型玩家七七2 小时前
技术抉择:微调还是 RAG?——以春节祝福生成为例
android·java·大数据·开发语言·人工智能·算法·安全
你撅嘴真丑2 小时前
蛇形填充数组 与 查找最接近的元素
数据结构·c++·算法
JXL18603 小时前
Dynamic programming
算法