[LeetCode]题解(python):106-Construct Binary Tree from Inorder and Postorder Traversal
2016-03-09 15:02
561 查看
[b]题目来源:[/b]
https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
[b]题意分析:[/b]
给出一颗二叉树的中序遍历和后续遍历,还原这个树。
[b]题目思路:[/b]
这题和上一题类似,用递归的思想,先根据后序遍历的最后一个确定根节点,然后将中序遍历分成两部分,接着递归就可以了。
[b]代码(python):[/b]
View Code
https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
[b]题意分析:[/b]
给出一颗二叉树的中序遍历和后续遍历,还原这个树。
[b]题目思路:[/b]
这题和上一题类似,用递归的思想,先根据后序遍历的最后一个确定根节点,然后将中序遍历分成两部分,接着递归就可以了。
[b]代码(python):[/b]
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def buildTree(self, inorder, postorder): """ :type inorder: List[int] :type postorder: List[int] :rtype: TreeNode """ def dfs(ibegin,iend,pbegin,pend): if pbegin >= pend: return None if pbegin == pend - 1: return TreeNode(postorder[pend - 1]) i = inorder.index(postorder[pend - 1]) - ibegin ans = TreeNode(postorder[pend - 1]) ans.left = dfs(ibegin,ibegin+i,pbegin,pbegin + i) ans.right = dfs(ibegin + 1 + i,iend,pbegin + i,pend - 1) return ans return dfs(0,len(inorder),0,len(postorder))
View Code
相关文章推荐
- PYthon psycopg2 数据库使用学习
- Python 中实现装饰器时使用 @functools.wraps 的理由
- python代码覆盖工具Coverage.py
- Python在Win7上重新安装出现的问题 2.7.11
- Java调用Python开发环境配置(Eclipse+Jython+PyDev)
- python学习笔记三--字典的使用
- Python Windows环境安装配置,以及Eclipse+Pydev开发
- 技术分享:如何用Python和PyInstaller编写Windows恶意代码
- Python装饰器基础详解
- 安装opencv-python 开发环境
- pip安装及使用详解
- python 调整图片大小源代码
- learn python the hardest way
- python 一个简单的依靠文件来判断key是否重复的方法
- 标准爬虫初探,来自Python之父的大餐!
- python创建任意大小的文件
- 【python】编程语言入门经典100例--30
- python socket
- 关于python subprocess的popen
- python—networkx:各个布局的源代码