【LeetCode】889. Construct Binary Tree from Preorder and Postorder Traversal 解题报告(Python & C++)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目描述
Return any binary tree that matches the given preorder and postorder traversals.
Values in the traversals pre and post are distinct positive integers.
Example 1:
Input: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
Output: [1,2,3,4,5,6,7]
Note:
- 1 <= pre.length == post.length <= 30
- pre[] and post[] are both permutations of 1, 2, …, pre.length.
- It is guaranteed an answer exists. If there exists multiple answers, you can return any of them.
题目大意
根据先序遍历和后序遍历,重建二叉树。
解题方法
讲道理的话,只知道前序和后序遍历是没法确定一棵二叉树的。所以,这个题指明了不含重复元素,而且如果有多棵二叉树返回其中的一种即可。
其实做法还是很简单的。前序和后序的遍历并没有打乱整棵树的关系,一棵树的节点在两种遍历方式所得到的还都是在一块的。
所以pre[0]是根节点,也就是post[-1];
post[-2]时候右子树的根节点,因此在前序遍历中找到post[-2]的位置idx就能分开两棵子树。
# 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 constructFromPrePost(self, pre, post):
"""
:type pre: List[int]
:type post: List[int]
:rtype: TreeNode
"""
if not pre or not post: return None
root = TreeNode(pre[0])
if len(pre) == 1:
return root
idx = pre.index(post[-2])
root.left = self.constructFromPrePost(pre[1:idx], post[:idx-1])
root.right = self.constructFromPrePost(pre[idx:], post[idx-1:-1])
return root
下面C++代码为了防止平凡的构建子数组,所以使用索引的方式切割数组。C++中,如果函数使用传值的方式进行参数传递,就会调用对象的拷贝构造函数,使得代码效率变慢。所以,一般使用传引用的方式加快函数传参的次数。下面的代码中,pre 和 post使用引用传递,[a,b]表示目前处理的pre区间,[c,d]表示目前处理的post区间。
代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* constructFromPrePost(vector<int>& pre, vector<int>& post) {
const int N = pre.size();
for (int i = 0; i < N; i++) m_[post[i]] = i;
return construct(pre, post, 0, N - 1, 0, N - 1);
}
private:
unordered_map<int, int> m_;
// pre[a, b], post[c, d]
TreeNode* construct(vector<int>& pre, vector<int>& post, int a, int b, int c, int d) {
TreeNode* root = new TreeNode(pre[a]);
if (a == b) return root;
int t = pre[a + 1];
int idx = m_[t];
int len = idx - c + 1;
root->left = construct(pre, post, a + 1, a + len, c, c + len - 1);
if (idx + 1 == d) return root;
root->right = construct(pre, post, a + len + 1, b, idx + 1, d - 1);
return root;
}
};
参考资料:
日期
2018 年 9 月 4 日 ———— 迎接明媚的阳光!
2018 年 12 月 8 日 —— 今天球打的不错,很舒服
【LeetCode】889. Construct Binary Tree from Preorder and Postorder Traversal 解题报告(Python & C++)的更多相关文章
- [LeetCode] 889. Construct Binary Tree from Preorder and Postorder Traversal 由先序和后序遍历建立二叉树
Return any binary tree that matches the given preorder and postorder traversals. Values in the trave ...
- LeetCode 889. Construct Binary Tree from Preorder and Postorder Traversal
原题链接在这里:https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/ 题 ...
- (二叉树 递归) leetcode 889. Construct Binary Tree from Preorder and Postorder Traversal
Return any binary tree that matches the given preorder and postorder traversals. Values in the trave ...
- 【LeetCode】106. Construct Binary Tree from Inorder and Postorder Traversal 解题报告
[LeetCode]106. Construct Binary Tree from Inorder and Postorder Traversal 解题报告(Python) 标签: LeetCode ...
- LC 889. Construct Binary Tree from Preorder and Postorder Traversal
Return any binary tree that matches the given preorder and postorder traversals. Values in the trave ...
- LeetCode: Construct Binary Tree from Preorder and Inorder Traversal 解题报告
Construct Binary Tree from Preorder and Inorder Traversal Given preorder and inorder traversal of a ...
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal 解题报告
Construct Binary Tree from Inorder and Postorder Traversal Given inorder and postorder traversal of ...
- 【原创】leetCodeOj ---Construct Binary Tree from Preorder and Inorder Traversal 解题报告
原题地址: https://oj.leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ 题目 ...
- C++版-剑指offer 面试题6:重建二叉树(Leetcode105. Construct Binary Tree from Preorder and Inorder Traversal) 解题报告
剑指offer 重建二叉树 提交网址: http://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6?tpId=13&tq ...
随机推荐
- typora 图床配置方法
学习计算机的同学,在日常学习中难免会记笔记,写文档.相信大家记笔记大部分使用的都是 Markdown 吧,如果到现在还没接触,那我强烈建议你去学习一下,大概几分钟就可以搞定它. 注:下文用到的所有软件 ...
- Levenshtein莱文斯坦算法在项目中的应用
简介 根据维基百科的描述,在信息理论.语言学和计算机科学中,莱文斯坦距离是一个测量两个序列之间差异的字符串度量.非正式地,两个单词之间的莱文斯坦距离是将一个单词改变为另一个单词所需的最小单字符编辑次数 ...
- 学习java的第十四天
一.今日收获 1.完成了手册第二章没有验证完成的例题 2.预习了第三章的算法以及for语句与if语句的用法 二.今日难题 1.验证上出现问题,没有那么仔细. 2.第二章还有没有完全理解的问题 三.明日 ...
- Spark(十六)【SparkStreaming基本使用】
目录 一. SparkStreaming简介 1. 相关术语 2. SparkStreaming概念 3. SparkStreaming架构 4. 背压机制 二. Dstream入门 1. WordC ...
- Spark的shuffle和MapReduce的shuffle对比
目录 MapperReduce的shuffle Spark的shuffle 总结 MapperReduce的shuffle shuffle阶段划分 Map阶段和Reduce阶段 任务 MapTask和 ...
- 零基础学习java------day12------数组高级(选择排序,冒泡排序,二分查找),API(Arrays工具类,包装类,BigInteger等数据类型,Math包)
0.数组高级 (1)选择排序 它的工作原理是每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的起始位置 ...
- 一起手写吧!promise.all
Promise.all 接收一个 promise 对象的数组作为参数,当这个数组里的所有 promise 对象全部变为resolve或 有 reject 状态出现的时候,它才会去调用 .then 方法 ...
- OpenStack之七: compute服务(端口8774)
注意此处的bug,参考o版 官网地址 https://docs.openstack.org/nova/stein/install/controller-install-rdo.html 控制端配置 # ...
- 重量级&轻量级
重量级 就是说包的大小,还有就是与个人项目的耦合程度,重量级的框架与项目耦合程度大些 代表EJB容器的服务往往是"买一送三",不要都不行 轻量级 就是相对较小的包,当然与项目的耦合 ...
- 【spring AOP】@Pointcut的12种用法
@Pointcut用来标注在方法上来定义切入点. 使用格式:@ 注解(value="表达标签 (表达式格式)").如:@Pointcut("execution(* com ...