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. 条款19 command 模式与好莱坞法则

    当一个函数对象被当做回调时候,就是一个command模式的实例 什么是回调? 回调就是框架知道什么时候干一些事情,但是具体干什么,或许框架一无所知(因为回调函数不是他设计的),而用户则知道发生一个特定 ...

  2. zencart用chrome无法登录后台

    再本地安装完zencart后,可以使用ie和Firefox登录网站后台,但是使用chrome登录时,页面闪一下,然后又跳转到登录页面. 按如下设置可以解决该问题: 中文版:商店设置->Sessi ...

  3. c#中操作word文档-一、模板方式写入

    转载自:http://blog.csdn.net/fujie724/article/details/5443322 适合模板写入 今天正好有人问我,怎么生成一个报表式的Word文档. 就是文字的样式和 ...

  4. [leetcode]_Valid Parentheses

    题目:判断给定字符串中的括号是否合法.题目中涉及三种符号'(' + ')' , '[' + ']' , '{' + '}'. 思路:利用stack来存储符号. 注意申请char型stack是: Sta ...

  5. JS中的控制函数调用:call(),apply()和bind()

    所有的函数都具有call(),apply()和bind()方法.它们可以在执行方法的时候用一个值指向this,并改变面向对象的作用域. apply方法: 以下的两种表达式是等价的: func(arg1 ...

  6. php5 date()获得的时间不是当前时间

    php自5.10起加入了时区的设置,在php中显示的时间都是格林威治标准时间,因此便与中国的用户会差八个小时. 修改php.ini中的 date.timezone 参数: [Date] ; Defin ...

  7. JSON (仅限本地)

    <script type="text/javascript"> setInterval(function() { $("#content").loa ...

  8. 【easyui】--combobox--赋值和获取选中的值

    //初始化下拉选框 $('#communityIdDiv').combobox({ url:basepath+"pushController/queryCommonityName" ...

  9. javascript雪花效果 注释版

    (function () { // 添加事件监听器 function addEvent(a, b, c) { if (a.addEventListener) a.addEventListener(b, ...

  10. ubuntun pptpd

    apt-get install pptpd 3.编辑pptpd.conf文件 vi /etc/pptpd.conf 取消注释下面内容 option /etc/ppp/pptpd-options loc ...