''' 6.7 二叉树重建 #============================================================================================= https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6?tpId=196&&tqId=37109&rp=1&ru=/activity/oj&qru=/ta/job-code-total/question-ranking 解题思路: 前序遍历:先根节点,再左子树,最后右子树 中序遍历:先左子树,再根节点,最后右子树 我们可以先从前序遍历的第一个元素得到根节点root=TreeNode(pre.pop(0)) 再从中序排序中找到根节点所在位置,以这个位置为中心,可以得到二叉树的左子树与右子树 二叉树可以分开看,左子树可以看成一个新的二叉树,不断细分,可以确定到每一个叶子节点 同理,右子树也可以,看成新的二叉树,我们可以通过递归来实现 特殊情况的考虑:无论哪一个遍历为空,题目所求都没有意义 #============================================================================================= ''' # -*- 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 not pre or not tin: return None #print('pre=',pre) #print('tin=',tin) #print('---') val = pre.pop(0) root = TreeNode(val) i = tin.index(val) root.left = self.reConstructBinaryTree(pre, tin[:i]) root.right = self.reConstructBinaryTree(pre, tin[i+1:]) return root pre = [1,2,3,4,5,6,7] tin = [3,2,4,1,6,5,7] Solution().reConstructBinaryTree(pre, tin)