python-leetcode-从前序与中序遍历序列构造二叉树

105. 从前序与中序遍历序列构造二叉树 - 力扣(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, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        if not preorder or not inorder:  # 如果任一遍历为空,返回 None
            return None
        
        # 根节点是前序遍历的第一个元素
        root_val = preorder[0]
        root = TreeNode(root_val)
        
        # 找到根节点在中序遍历中的位置
        root_index = inorder.index(root_val)
        
        # 划分左子树和右子树
        left_inorder = inorder[:root_index]
        right_inorder = inorder[root_index + 1:]
        
        left_preorder = preorder[1:1 + len(left_inorder)]
        right_preorder = preorder[1 + len(left_inorder):]
        
        # 递归构建左子树和右子树
        root.left = self.buildTree(left_preorder, left_inorder)
        root.right = self.buildTree(right_preorder, right_inorder)
        
        return root
            
相关推荐
椰萝Yerosius13 分钟前
[题解]2024CCPC郑州站——Z-order Curve
c++·算法
小曹要微笑16 分钟前
STM32F7 时钟树简讲(快速入门)
c语言·stm32·单片机·嵌入式硬件·算法
南山安25 分钟前
栈(Stack):从“弹夹”到算法面试题的进阶之路
javascript·算法·面试
2301_764441331 小时前
Python构建输入法应用
开发语言·python·算法
AI科技星1 小时前
为什么变化的电磁场才产生引力场?—— 统一场论揭示的时空动力学本质
数据结构·人工智能·经验分享·算法·计算机视觉
TheLegendMe2 小时前
贪心+线程安全单例
算法·哈希算法
豐儀麟阁贵3 小时前
8.5在方法中抛出异常
java·开发语言·前端·算法
Hacker_Oldv3 小时前
Python技能进阶:探索Selenium库,实现网页自动化测试与爬虫
自动化测试·软件测试·爬虫·python·selenium·职场和发展
胖咕噜的稞达鸭3 小时前
算法入门:滑动窗口--->找到字符串中所有的字母异位词,串联所有的子串,最小覆盖子串
数据库·redis·算法
小青龙emmm3 小时前
2025级C语言第二次周测(国教专用)题解
c语言·开发语言·算法