剑指offer:重建二叉树(Python)

题目描述

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

思路:

算法设计思想

  前序遍历序列的第一个元素为根结点,然后在中序遍历序列中寻找根节点位置(索引)。

  从中序遍历序列起始位置根结点的值的位置(不包含)为根结点左子树中序遍历序列;从中序遍历序列根结点的值的位置(不包含)到结束位置根结点右子树中序遍历序列;相应的,从前序遍历序列的第二个元素开始的根结点左子树结点数个元素的子序列为根结点左子树前序遍历序列,从下一个元素开始,直到结束位置的子序列为根结点右子树前序遍历序列。如图 2.7 所示,

 


# -*- 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
        if len(pre)==0:
            return None
        if len(pre)==1:
            return TreeNode(pre[0])
        else:
            res = TreeNode(pre[0])
            res.left = self.reConstructBinaryTree(pre[1:tin.index(pre[0])+1],tin[:tin.index(pre[0])])
            res.right = self.reConstructBinaryTree(pre[tin.index(pre[0])+1:],tin[tin.index(pre[0])+1:])
        return res

另外:Python List index()方法

index() 函数用于从列表中找出某个值第一个匹配项的索引位置。


猜你喜欢

转载自blog.csdn.net/u013129109/article/details/80590742