【剑指offer】4.重建二叉树[by Python]

题目描述

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

思路:

算法设计思想

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

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

 



     
     
  1. # -*- coding:utf-8 -*-
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7. class Solution:
  8. # 返回构造的TreeNode根节点
  9. def reConstructBinaryTree(self, pre, tin):
  10. # write code here
  11. if len(pre)== 0:
  12. return None
  13. if len(pre)== 1:
  14. return TreeNode(pre[ 0])
  15. else:
  16. res = TreeNode(pre[ 0])
  17. res.left = self.reConstructBinaryTree(pre[ 1:tin.index(pre[ 0])+ 1],tin[:tin.index(pre[ 0])])
  18. res.right = self.reConstructBinaryTree(pre[tin.index(pre[ 0])+ 1:],tin[tin.index(pre[ 0])+ 1:])
  19. return res

另外:Python List index()方法

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


题目描述

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

思路:

算法设计思想

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

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

 

扫描二维码关注公众号,回复: 6528490 查看本文章


  
  
  1. # -*- coding:utf-8 -*-
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7. class Solution:
  8. # 返回构造的TreeNode根节点
  9. def reConstructBinaryTree(self, pre, tin):
  10. # write code here
  11. if len(pre)== 0:
  12. return None
  13. if len(pre)== 1:
  14. return TreeNode(pre[ 0])
  15. else:
  16. res = TreeNode(pre[ 0])
  17. res.left = self.reConstructBinaryTree(pre[ 1:tin.index(pre[ 0])+ 1],tin[:tin.index(pre[ 0])])
  18. res.right = self.reConstructBinaryTree(pre[tin.index(pre[ 0])+ 1:],tin[tin.index(pre[ 0])+ 1:])
  19. return res

另外:Python List index()方法

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


猜你喜欢

转载自blog.csdn.net/qq_33487726/article/details/91044315