题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回
思路解析
二叉树的遍历考虑使用递归,前序遍历顺序为根节点–左节点–右节点,中序遍历顺序为左节点–根节点–右节点
根据前序遍历的第一个节点(根节点),在中序遍历找到根节点的索引位置,确定左右子树,对左右子树使用递归,直到到达叶子节点
具体代码
class Solution:
# 树的遍历使用递归
# pre为前序遍历,tin为中序遍历
def reConstructBinaryTree(self, pre, tin):
if len(pre) == 0:
return None
elif len(pre) == 1:
return TreeNode(pre[0])
else:
# root为根节点
root = TreeNode(pre[0])
# 通过根节点在中序序列中的位置划分出左右子树包含的节点
index = tin.index(root.val)
# 重建左子树
root.left = self.reConstructBinaryTree(pre[1:index+1], tin[:index])
# 重建右子树
root.right = self.reConstructBinaryTree(pre[index+1:], tin[index+1:])
return root