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
相关推荐
北冥湖畔的燕雀2 分钟前
C++智能指针:告别内存泄漏的利器
c++·算法
傻乐u兔5 分钟前
C语言进阶————数据在内存中的存储1
c语言·数据结构·算法
XH华12 分钟前
备战蓝桥杯,第三章:条件判断与循环
职场和发展·蓝桥杯
多米Domi01122 分钟前
0x3f 第42天 复习 10:39-11:33
算法·leetcode
thubier(段新建)24 分钟前
单招模考试卷模型思考(1)
算法·单招
议题一玩到28 分钟前
#leetcode# 1984. Minimum Difference Between Highest and Lowest of K Scores
数据结构·算法·leetcode
是娇娇公主~28 分钟前
算法——【最长回文子串】
c++·算法
你撅嘴真丑42 分钟前
计算2的N次方 和 大整数的因子
数据结构·c++·算法
孞㐑¥1 小时前
算法—前缀和
c++·经验分享·笔记·算法
yugi9878381 小时前
基于MATLAB的延迟求和(DAS)波束形成算法实现
开发语言·算法·matlab