输入二叉树的前序遍历的前序遍历和中序遍历的结果,重建该二叉树
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin): #pre为前序遍历,tin为中序遍历
# write code here
if len(pre) == 0: #如果前序遍历为空
return None
root = TreeNode(pre[0]) #根节点为前序遍历的第一个数字
i = tin.index(pre[0]) # i为根节点在中序遍历中的位置
root.left = self.reConstructBinaryTree(pre[1:1+i],tin[:i]) #获取左子树的前序遍历和中序遍历
root.right = self.reConstructBinaryTree(pre[1+i:],tin[i+1:]) #获取右子树的前序遍历和中序遍历
return root