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 小时前
(LeetCode-Hot100)53. 最大子数组和
java·算法·leetcode·职场和发展·go
生成论实验室4 小时前
即事经:一种基于生成论的宇宙、生命与文明新范式
人工智能·科技·神经网络·算法·信息与通信
王老师青少年编程4 小时前
csp信奥赛c++高频考点假期集训(分模块进阶)
数据结构·c++·算法·csp·高频考点·信奥赛·集训
癫狂的兔子6 小时前
【Python】【机器学习】K-MEANS算法
算法·机器学习·kmeans
Bear on Toilet6 小时前
递归_二叉树_50 . 从前序与中序遍历序列构造二叉树
数据结构·算法·leetcode·深度优先·递归
plus4s6 小时前
2月18日(82-84题)
c++·算法·动态规划
艾醒7 小时前
打破信息差——2026年2月19日AI热点新闻速览
算法
追随者永远是胜利者9 小时前
(LeetCode-Hot100)62. 不同路径
java·算法·leetcode·职场和发展·go
追随者永远是胜利者9 小时前
(LeetCode-Hot100)56. 合并区间
java·算法·leetcode·职场和发展·go
wu_asia9 小时前
每日一练伍
算法