# 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:
return None
rootVal = preorder[0]
root = TreeNode(rootVal)
if len(preorder) == 1:
return root
rootVal_idx = inorder.index(rootVal)
inorder_left = inorder[:rootVal_idx]
inorder_right = inorder[rootVal_idx + 1:]
preorder_left = preorder[1: 1 + len(inorder_left)]
preorder_right = preorder[1 + len(inorder_left):]
root.left = self.buildTree(preorder_left, inorder_left)
root.right = self.buildTree(preorder_right, inorder_right)
return root
此题请参考Leetcode106。Leetcode.106 从中序与后序遍历序列构造二叉树 Construct Binary Tree from Inorder and Postorder Traversal - Python 递归法_princey2100的博客-CSDN博客