根据一棵树的前序遍历与中序遍历构造二叉树。
注意:你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
根节点preorder[0]
在中序遍历数列中的位置index
,index
左边的部分为左子树的中序遍历序列,index
右边的为右子树的中序遍历序列。相应的在前序遍历中,从索引1
开始后的部分为对应的左子树和右子树的前序遍历序列,它们的元素个数和中序遍历中划分后的个数相同。 然后将左子树和右子树分别当作一棵新的二叉树,递归调用函数进行重建。
AC code
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
if len(preorder) == 0: return None
if len(preorder) == 1:
return TreeNode(preorder[0])
else:
# 二叉树的根节点
root = TreeNode(preorder[0])
# 子树根节点在中序遍历中的索引
index = inorder.index(preorder[0])
# 使用左子树对应的前序遍历序列和中序遍历序列重建子树
root.left = self.buildTree(preorder[1: index + 1], inorder[: index])
# 使用右子树对应的前序遍历序列和中序遍历序列重建子树
root.right = self.buildTree(preorder[index + 1:], inorder[index + 1: ])
return root