思路
递归:前序遍历的第 1 个结点一定是二叉树的根结点;
在中序遍历中,根结点把中序遍历序列分成了两个部分,左边部分构成了二叉树的根结点的左子树,右边部分构成了二叉树的根结点的右子树。
代码
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
# write code here
#采用递归的方法可以实现
if not pre or not tin:
#if len(pre)==0:
return None
root_data = TreeNode(pre[0])
i = tin.index(pre[0])
root_data.left = self.reConstructBinaryTree(pre[1:i+1],tin[:i])
root_data.right = self.reConstructBinaryTree(pre[i+1:],tin[i+1:])
return root_data