Careercup - Google面试题 - 5162732873580544
2014-05-08 08:26
原题:
Given a preorder traversal, create a binary search tree in optimized time
题目:给定一个二叉搜索树的前序遍历,请重建这棵树。要求最优化算法。
解法1:这人每次出题都要求“最优算法”,自己写的代码却实在让人汗颜,让人觉得这家伙就是懒得思考,想从别人那儿问答案。前序遍历的顺序是“根左右”,那么根节点之后所有小于根的部分就是左子树,后面就是右子树了。怎么找这条分界线呢?可以顺着找。那么算法的复杂度就是O(n * log(n))了。复杂度的证明参考归并排序即可。这个算法可行,但不是最优。
代码:
// http://www.careercup.com/question?id=5162732873580544
#include <iostream>
#include <vector>
using namespace std; struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int _val = ): val(_val), left(nullptr), right(nullptr) {};
}; void constructBSTFromPreorderTraversal(vector<int> &v, int ll, int rr, TreeNode *&root)
{
root = new TreeNode(v[ll]); int i = ll + ;
while (i <= rr && v[i] < v[ll]) {
++i;
}
if (ll + <= i - ) {
constructBSTFromPreorderTraversal(v, ll + , i - , root->left);
}
if (i <= rr) {
constructBSTFromPreorderTraversal(v, i, rr, root->right);
}
} void inorderTraversal(TreeNode *root)
{
if (nullptr == root) {
return;
}
inorderTraversal(root->left);
cout << root->val << ' ';
inorderTraversal(root->right);
} void clearTree(TreeNode *&root)
{
if (nullptr == root) {
return;
}
clearTree(root->left);
clearTree(root->right);
delete root;
root = nullptr;
} int main()
{
vector<int> v;
int n;
int i;
TreeNode *root; while (cin >> n && n > ) {
v.resize(n);
for (i = ; i < n; ++i) {
cin >> v[i];
}
root = nullptr;
constructBSTFromPreorderTraversal(v, , n - , root);
inorderTraversal(root);
cout << endl; clearTree(root);
v.clear();
} return ;
}
解法2:既然遍历是O(n)时间完成的,重建应该也可以做到O(n)。我的思路,是比较三个节点的值:父节点,当前节点,新节点。根据它们之间的大小关系可以判断新的节点应该插入在哪儿。代码中的关键部分很短,所以不需要多余解释了。其中用到了一个节点栈,用于回溯。所以这个算法用递归来写也是同样直观的。
// http://www.careercup.com/question?id=5162732873580544
#include <iostream>
#include <vector>
using namespace std; struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int _val = ): val(_val), left(nullptr), right(nullptr) {};
}; void inorderTraversal(TreeNode *root)
{
if (nullptr == root) {
return;
}
inorderTraversal(root->left);
cout << root->val << ' ';
inorderTraversal(root->right);
} void clearTree(TreeNode *&root)
{
if (nullptr == root) {
return;
}
clearTree(root->left);
clearTree(root->right);
delete root;
root = nullptr;
} int main()
{
vector<int> v;
int n;
int i;
TreeNode *root;
TreeNode *tmp;
vector<TreeNode *> st; while (cin >> n && n > ) {
v.resize(n);
for (i = ; i < n; ++i) {
cin >> v[i];
} root = new TreeNode(v[]);
st.push_back(root);
for (i = ; i < n; ++i) {
if (v[i] < st[st.size() - ]->val) {
tmp = new TreeNode(v[i]);
st[st.size() - ]->left = tmp;
st.push_back(tmp);
} else if (st.size() == || v[i] < st[st.size() - ]->val) {
tmp = new TreeNode(v[i]);
st[st.size() - ]->right = tmp;
st.push_back(tmp);
} else {
st.pop_back();
--i;
}
} inorderTraversal(root);
cout << endl; v.clear();
st.clear();
clearTree(root);
} return ;
}
Careercup - Google面试题 - 5162732873580544的更多相关文章
- Careercup - Google面试题 - 5732809947742208
2014-05-03 22:10 题目链接 原题: Given a dictionary, and a list of letters ( or consider as a string), find ...
- Careercup - Google面试题 - 5085331422445568
2014-05-08 23:45 题目链接 原题: How would you use Dijkstra's algorithm to solve travel salesman problem, w ...
- Careercup - Google面试题 - 4847954317803520
2014-05-08 21:33 题目链接 原题: largest number that an int variable can fit given a memory of certain size ...
- Careercup - Google面试题 - 6332750214725632
2014-05-06 10:18 题目链接 原题: Given a ,) (,) (,), (,) should be returned. Some suggest to use Interval T ...
- Careercup - Google面试题 - 5634470967246848
2014-05-06 07:11 题目链接 原题: Find a shortest path ,) to (N,N), assume is destination, use memorization ...
- Careercup - Google面试题 - 5680330589601792
2014-05-08 23:18 题目链接 原题: If you have data coming in rapid succession what is the best way of dealin ...
- Careercup - Google面试题 - 5424071030341632
2014-05-08 22:55 题目链接 原题: Given a list of strings. Produce a list of the longest common suffixes. If ...
- Careercup - Google面试题 - 5377673471721472
2014-05-08 22:42 题目链接 原题: How would you split a search query across multiple machines? 题目:如何把一个搜索que ...
- Careercup - Google面试题 - 6331648220069888
2014-05-08 22:27 题目链接 原题: What's the tracking algorithm of nearest location to some friends that are ...
随机推荐
- 比特币钱包应用breadwallet源码
breadwallet是一款安全.可靠和便捷的比特币钱包,可使用户免于恶意软件和其他应用中常见的安全问题的骚扰,充分利用了iOS提供的安全功能,包括AES硬件加密.app沙盒和数据保护.代码签名以及k ...
- SDUST作业10 Problem J: 提取缩略词
Description 在英文文献中,尤其是专业文献中,经常有很多的缩略词,如CPU代表Central Processing Unit等.为了方便学习,Qili决定从一批英文论文中提取出所有的缩略词以 ...
- .NET程序员爱上网站[整理]
1.博客园(代码改变世界) http://www.cnblogs.com 2.开源中国社区(开源软件发现.使用和交流平台) http://www.oschina.net 3.CSDN(中国最大的IT社 ...
- 二、MongoDB的基础知识简介
1.文档.集合和数据库 a).文档:因为MongoDB是面向文档的数据库,那么可想而知文档是它的基本单元,相当于关系型数据库中的行! Ⅰ.它是由键值对组成的一个有序集:注:键不能为空且是字符串类型的. ...
- MongoDB的安装小结
正在做毕业设计,想尝试着用mongoDB来做数据库,之前没有接触过,然后,就在网上找资料,自己捣鼓,弄了好久才算上真正的把它安上,好心累.... 网上有很多安装教程,大同小异,这里呢,我只是想记录一下 ...
- asp.net实现md5加密方法详解
MD5加密简单的说就是把一段明文 通过某种运算方式 求出密文. 例如:明文为:abcdefg 通过一些列运算 得到 密文 7ac66c0f148de9519b8bd264312c4d64 它具有两个特 ...
- MySQL: ON DUPLICATE KEY UPDATE 用法 避免重复插入数据
INSERT INTO osc_visit_stats(stat_date,type,id,view_count) VALUES (?,?,?,?) ON DUPLICATEKEY UPDATE vi ...
- Json 调用 天气API 实例
百度了一下,找了点别人的方法改进了一下. 获取天气网址:http://www.weather.com.cn/html/weather/101210701.shtml这里是温州的,当然其他城市自己搜索一 ...
- 19) Java并发
>synchronized synchronized 关键字,它包括两种用法:synchronized 方法和 synchronized 块. 1>synchronized 方法:通过在 ...
- Python之MySql操作
1.安装驱动 输入命令:pip install MySQL-python 2.直接使用驱动 #coding=utf-8 import MySQLdb conn= MySQLdb.connect( ho ...