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
相关推荐
geats人山人海1 小时前
算法基础第六讲 图论
算法·深度优先·图论
Rain的Java大神之路3 小时前
LeetCode 45 跳跃游戏 II:大厂面试官最爱追问的贪心题,我把骨头给你拆干净了
java·后端·leetcode
风落青芜4 小时前
排序算法(四):归并排序、计数排序与算法总结
c语言·开发语言·数据结构·算法·排序算法
@陈小鱼5 小时前
基于InceptionTime网络的PPG无创血压估计算法研究
人工智能·python·算法·回归·开源·ppg·血压估计
Rocky Ding*6 小时前
【三年面试五年模拟】2026-09-23 恒生电子AI Agent应用开发岗面试全解析
人工智能·深度学习·机器学习·面试·职场和发展·aigc·ai-native
liulilittle11 小时前
认识麻将 —— 流水及对账
算法·游戏·lua·对账·流水·资金·玩法
郝学胜-神的一滴14 小时前
Effective Python 条款44:善用属性注解
开发语言·c++·vscode·python·算法·stl
嵌入式 Linux手记1 天前
柔性数组:为什么写 data[] 而不是 data[0]
linux·c语言·面试·职场和发展·嵌入式·柔性数组
青少儿编程课堂1 天前
第十八届蓝桥杯青少组图形化真题:校园分形雪花绘制解析(全国青少年信息素养大赛·电子学会图形化考级冲刺)
c++·python·算法·bfs·信息学竞赛