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
相关推荐
阿文的代码库4 小时前
换根技巧实例分析:最小高度树
算法·动态规划
dyxal4 小时前
Louvain 算法:让网络自己“报团取暖”的发现者
开发语言·算法
计算机安禾4 小时前
【c++面向对象编程】第41篇:函数模板与类模板:泛型编程的基石
开发语言·c++·算法
SilentSamsara5 小时前
属性查找顺序:实例 → 类 → 父类的完整 MRO
开发语言·python·算法·青少年编程
不知名的老吴5 小时前
浅谈:树形动态规划中的换根技巧
算法·动态规划
一条大祥脚5 小时前
2021-2022 ICPC Southwestern Europe Regional Contest
算法·深度优先·图论
罗湖老棍子5 小时前
The xor-longest Path(信息学奥赛一本通- P1478)
算法·字符串·字典树··lca最近公共祖先
whuhewei5 小时前
React diff算法为什么是DFS,不是BFS
算法·react.js·深度优先
EdmundXjs6 小时前
大模型核心概念解读
人工智能·算法
lookaroundd6 小时前
llm-compressor 普通量化调用链分析
python·算法