剑指offer:重建二叉树(Python)
2018-03-06 10:40
260 查看
题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。(事实上,返回的是二叉树的根节点)思路
前序遍历=“根左右”,中序遍历=“左根右”。由前序遍历序列获得根节点及其位置——>由根节点和对应位置,分别获得:左子树的前序遍历序列和中序遍历序列,以及右子树的前序遍历序列和中序遍历序列——>分别递归左子树的前中序列,右子树的前中序列。
Python代码
class Solution: def getBSTwithPreTin(self, pre, tin): if len(pre)==0 | len(tin)==0: return None root = TreeNode(pre[0]) for order,item in enumerate(tin): if root .val == item: root.left = self.getBSTwithPreTin(pre[1:order+1], tin[:order]) root.right = self.getBSTwithPreTin(pre[order+1:], tin[order+1:]) return root class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None if __name__ == '__main__': solution = Solution() preorder_seq = [1,2,4,7,3,5,6,8] midorder_seq = [4,7,2,1,5,3,8,6] treeRoot = solution.getBSTwithPreTin(preorder_seq, midorder_seq)
相关文章推荐
- python实现剑指offer系列:重建二叉树
- 剑指offer--重建二叉树[根据二叉树的先序、中序遍历结果重建二叉树]
- 重建二叉树(参考剑指offer)
- (剑指Offer)面试题6:重建二叉树
- 剑指Offer面试题:5.重建二叉树
- 《剑指Offer》读书笔记---面试题6:重建二叉树
- 【剑指offer系列】 重建二叉树___6
- 重建二叉树(剑指offer)
- Python实现重建二叉树的三种方法详解
- python剑指offer系列把二叉树打印成多行
- (剑指offer笔记)根据前序遍历和后序遍历重建二叉树
- 剑指offer--重建二叉树
- 剑指offer(四) 重建二叉树
- Python利用前序和中序遍历结果重建二叉树的方法
- 剑指Offer——重建二叉树
- 剑指offer之二叉树的镜像(Python)
- 剑指Offer:面试题6 重建二叉树
- JAVA实现重建二叉树(《剑指offer》)
- Python:重建二叉树
- 《剑指Offer》学习笔记--面试题6:重建二叉树