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
            
相关推荐
2201_75698909几秒前
C++中的事件驱动编程
开发语言·c++·算法
会飞的战斗鸡6 分钟前
JS中的链表(含leetcode例题)
javascript·leetcode·链表
多米Domi01111 分钟前
0x3f 第48天 面向实习的八股背诵第五天 + 堆一题 背了JUC的题,java.util.Concurrency
开发语言·数据结构·python·算法·leetcode·面试
2301_8223776512 分钟前
模板元编程调试方法
开发语言·c++·算法
故以往之不谏28 分钟前
函数--值传递
开发语言·数据结构·c++·算法·学习方法
渐暖°36 分钟前
【leetcode算法从入门到精通】5. 最长回文子串
vscode·算法·leetcode
今天_也很困37 分钟前
LeetCode热题100-560. 和为 K 的子数组
java·算法·leetcode
v_for_van1 小时前
力扣刷题记录2(无算法背景,纯C语言)
c语言·算法·leetcode
2301_811232981 小时前
低延迟系统C++优化
开发语言·c++·算法
alphaTao1 小时前
LeetCode 每日一题 2026/1/26-2026/2/1
算法·leetcode