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
相关推荐
Eloudy8 分钟前
直接法 读书笔记 06 第6章 LU分解
人工智能·算法·ai·hpc
仰泳的熊猫23 分钟前
题目1531:蓝桥杯算法提高VIP-数的划分
数据结构·c++·算法·蓝桥杯
刘琦沛在进步1 小时前
如何计算时间复杂度与空间复杂度
数据结构·c++·算法
m0_672703311 小时前
上机练习第30天
数据结构·算法
935961 小时前
机考31 翻译25 单词18
c语言·算法
每天要多喝水1 小时前
单调栈Day36:接雨水
算法
AI科技星2 小时前
时空的几何本源与物理现象的建构:论统一场论的宇宙二元论与观察者中心范式
人工智能·线性代数·算法·矩阵·数据挖掘
CelestialYuxin2 小时前
A.R.I.S.系统:YOLOx在破碎电子废料分拣中的新探索
人工智能·深度学习·算法
_ziva_2 小时前
YOLO 目标检测算法深度解析:从原理到实战价值
算法·yolo·目标检测
Jason_Honey22 小时前
【蚂蚁金服Agent算法岗一面】
人工智能·算法·自然语言处理·面试