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