Careercup - Microsoft面试题 - 5799446021406720
2024-09-07 05:40:55
2014-05-12 07:17
原题:
Given below is a tree/trie
A
B c D
e F
a<b<e<>>c<>d<f<>>>
above string represents the following trie/tree (visualize) and assume that there exisits a serialize method that performs above.
Now, write a deserialize method so that above string to an object model of the following
TreeNode
TreeNode[] children
题目:给定以上的字典树序列化方法,请写出相应的反序列化方法。
解法:观察序列化的字符串,可以发现序列化的规则是“字母<若干个子树>”。用一个栈就可以写出比较简洁的反序列化代码。
代码:
// http://www.careercup.com/question?id=5799446021406720
#include <iostream>
#include <stack>
#include <string>
#include <vector>
using namespace std; struct TrieNode {
char ch;
vector<TrieNode *> child;
TrieNode(char _ch = ): ch(_ch), child(vector<TrieNode *>()) {};
}; TrieNode *deserializeFromString(const string &str)
{
TrieNode *root;
TrieNode *ptr;
stack<TrieNode *> st; int i, n; root = nullptr;
n = (int)str.length();
i = ;
while (i < n) {
if (str[i] == '>') {
st.pop();
++i;
} else {
ptr = new TrieNode(str[i]);
i += ;
if (st.empty()) {
root = ptr;
} else {
(st.top()->child).push_back(ptr);
}
st.push(ptr);
}
} return root;
} void preorderTraversal(TrieNode *root)
{
if (root == nullptr) {
return;
}
cout << root->ch << ' ';
for (int i = ; i < (int)root->child.size(); ++i) {
preorderTraversal(root->child[i]);
}
} int main()
{
TrieNode *root = nullptr;
string str; while (cin >> str) {
root = deserializeFromString(str);
preorderTraversal(root);
cout << endl;
} return ;
}
最新文章
- 页置换算法FIFO、LRU、OPT
- docfx daylybuild
- 【Jquery】$.Deferred 对象
- BM算法 Boyer-Moore高质量实现代码详解与算法详解
- daatable动态创建
- SFTPTool 和 FTPTooL.java
- ubuntu配置多个DNS
- Kafka - SQL 引擎
- SQL-三级分类查询
- File(File f, String child) File(String parent, String child)
- typeahead使用ajax补全输入框的方法
- GDScript 格式化字符串
- windows多线程同步互斥--总结
- Go学习笔记(二)搭建Visual Studio Code调试环境
- 适用于 Windows 7 SP1、Windows Server 2008 R2 SP1 和 Windows Server 2008 SP2 的 .NET Framework 4.5.2 仅安全更新说明:2017 年 9 月 12 日
- WebApp与Native App有何区别
- mybatis学习------打包xml映射文件
- 【51nod】1061 最复杂的数 V2
- python-Unix套接字
- 自定义标签(JspFragment类、invoke方法、开发带属性的标签)