原题
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
My Answer
算法设计思想:
前序遍历序列的第一个元素为根结点的值,然后在中序遍历序列中寻找根节点的值的位置(索引)。
从中序遍历序列的起始位置到根结点的值的位置(不包含)为根结点左子树的中序遍历序列;从中序遍历序列的根结点的值的位置(不包含)到结束位置为根结点右子树的中序遍历序列;相应的,从前序遍历序列的第二个元素开始的根结点左子树结点数个元素的子序列为根结点左子树的前序遍历序列,从下一个元素开始,直到结束位置的子序列为根结点右子树的前序遍历序列。如图 2.7 所示,
采用了递归的思路进行求解,既然采用了递归,自然要有返回条件,返回条件无非就是当 len(left_tree) = 0 or 1
以及 len(right_tree) = 0 or 1
的时候,代码实现如下:
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
# write code here
# note: the input of pre and tin are list, so we can directly use
# the number of list to construct the binary tree.
if len(pre) == 0 or len(tin)== 0 :
return
if len(pre) == 1:
return TreeNode(pre[0])
if len(tin) == 1:
return TreeNode(tin[0])
root_index = tin.index(pre[0])
left = tin[0: root_index]
right = tin[root_index+1:]
root = TreeNode(pre[0])
root.left = self.reConstructBinaryTree(pre[1:root_index+1], tin[:root_index])
root.right = self.reConstructBinaryTree(pre[root_index+1:], tin[root_index+1:])
return root