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的更多相关文章

  1. Careercup - Google面试题 - 5732809947742208

    2014-05-03 22:10 题目链接 原题: Given a dictionary, and a list of letters ( or consider as a string), find ...

  2. Careercup - Google面试题 - 5085331422445568

    2014-05-08 23:45 题目链接 原题: How would you use Dijkstra's algorithm to solve travel salesman problem, w ...

  3. Careercup - Google面试题 - 4847954317803520

    2014-05-08 21:33 题目链接 原题: largest number that an int variable can fit given a memory of certain size ...

  4. Careercup - Google面试题 - 6332750214725632

    2014-05-06 10:18 题目链接 原题: Given a ,) (,) (,), (,) should be returned. Some suggest to use Interval T ...

  5. Careercup - Google面试题 - 5634470967246848

    2014-05-06 07:11 题目链接 原题: Find a shortest path ,) to (N,N), assume is destination, use memorization ...

  6. Careercup - Google面试题 - 5680330589601792

    2014-05-08 23:18 题目链接 原题: If you have data coming in rapid succession what is the best way of dealin ...

  7. Careercup - Google面试题 - 5424071030341632

    2014-05-08 22:55 题目链接 原题: Given a list of strings. Produce a list of the longest common suffixes. If ...

  8. Careercup - Google面试题 - 5377673471721472

    2014-05-08 22:42 题目链接 原题: How would you split a search query across multiple machines? 题目:如何把一个搜索que ...

  9. Careercup - Google面试题 - 6331648220069888

    2014-05-08 22:27 题目链接 原题: What's the tracking algorithm of nearest location to some friends that are ...

随机推荐

  1. [视频]物联网应用-ARM mbed-来至MultiTech Systems的解决方案

    ARM公司面向物联网及可穿戴市场,近期可谓是动作频频,先是发布了专为物联网及可穿戴领域而生的Cortex-M7架构,接着又发布了mbed物联网操作系统.意图在物联网领域构筑一套坚不可摧的生态系统. 这 ...

  2. 安装zabbix

    安装zabbix 1. 准备好lamp架构(安装好mysql,php) 2.在数据库中授权: MariaDB [(none)]> create database zabbix charset u ...

  3. Aspose插件

    Eclipse安装地址: http://apps.aspose.com/marketplace/eclipse/asposewizardrepo

  4. Silverlight DataGrid数据行背景颜色控制

    sdk:DataGrid数据绑定后,部分特殊的行需要用不同的背景颜色来显示.(注册DataGrid的LoadingRow事件) private void radGridView_LoadingRow( ...

  5. ThinkPHP整合支付宝即时到账接口调用

    首先是在支付宝的蚂蚁金服开放平台下载PHP的demo: https://doc.open.alipay.com/doc2/detail?treeId=62&articleId=103566&a ...

  6. PHP函数:生成N个不重复的随机数

    思路:将生成的随机数存入数组,再在数组中去除重复的值,即可生成一定数量的不重复随机数. 程序: <?php /* * array unique_rand( int $min, int $max, ...

  7. 添加常驻Notification

    private static final int NOTIFICATION_ID=250; //用来标示notification,通过notificatinomanager来发布同样标示的notifi ...

  8. Oracle存储过程学习备忘

    之前的项目使用存储过程很少,但在实际的项目中,存储过程的使用是必不可少的. 存储过程是一组为了完成特定功能的SQL 语句 集,经编译后存储在数据库中:存储过程创建后,一次编译在程序中可以多次调用,对安 ...

  9. 手动书写小代码-foreach实现机制

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.C ...

  10. hdu 1874 畅通工程续

    题目连接 http://acm.hdu.edu.cn/showproblem.php?pid=1874 畅通工程续 Description 某省自从实行了很多年的畅通工程计划后,终于修建了很多路.不过 ...