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
相关推荐
学逆向的14 分钟前
C 内存属性
c语言·开发语言·算法·网络安全
lengxuenong34 分钟前
树状数组 · 信息学学习手册1-求和3个模板
c++·学习·算法·青少年编程
zhangminghuan39 分钟前
前端面试应对技巧
前端·面试·职场和发展
ComputerInBook43 分钟前
泛函分析概观
人工智能·算法·机器学习·泛函分析
Nuanyt1 小时前
LeetCode Hot100 刷题笔记 · 普通数组专题
java·笔记·算法·leetcode
q27551300421 小时前
AS8132 DP转HDMI 4K60(420)被动式 国产性价比AS方案
linux·算法·硬件架构·dash
安全指北针1 小时前
密态计算:数据 “可用不可见” 的底层技术解析
人工智能·算法
Jmyd01232 小时前
3D 扫描仪选型技术拆解:精度、点云与软件链路
人工智能·算法·3d·三维数字化
xxxiugou1232 小时前
链表算法题精讲:从两数相加到K组翻转
数据结构·c++·算法·链表
梦帮科技2 小时前
量子纠缠网络与量子隐形传态攻防:量子中继器信道串扰、纠缠态保真度降解与量子路由劫持
开发语言·网络·人工智能·算法·自动化·php