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 ;
}

最新文章

  1. 页置换算法FIFO、LRU、OPT
  2. docfx daylybuild
  3. 【Jquery】$.Deferred 对象
  4. BM算法  Boyer-Moore高质量实现代码详解与算法详解
  5. daatable动态创建
  6. SFTPTool 和 FTPTooL.java
  7. ubuntu配置多个DNS
  8. Kafka - SQL 引擎
  9. SQL-三级分类查询
  10. File(File f, String child) File(String parent, String child)
  11. typeahead使用ajax补全输入框的方法
  12. GDScript 格式化字符串
  13. windows多线程同步互斥--总结
  14. Go学习笔记(二)搭建Visual Studio Code调试环境
  15. 适用于 Windows 7 SP1、Windows Server 2008 R2 SP1 和 Windows Server 2008 SP2 的 .NET Framework 4.5.2 仅安全更新说明:2017 年 9 月 12 日
  16. WebApp与Native App有何区别
  17. mybatis学习------打包xml映射文件
  18. 【51nod】1061 最复杂的数 V2
  19. python-Unix套接字
  20. 自定义标签(JspFragment类、invoke方法、开发带属性的标签)

热门文章

  1. ${fn:} 函数
  2. 【Shell脚本学习22】Shell 函数:Shell函数返回值、删除函数、在终端调用函数
  3. 【extjs6学习笔记】1.10 初始: 定义类
  4. python any all函数
  5. 自己实现的简单的grid
  6. JS整数验证
  7. NetTime——c++实现计算机时间与网络时间的更新
  8. java Vamei快速教程10 接口的继承和抽象类
  9. linux 命令——36 diff(转)
  10. tomcat 启动显示指定的服务未安装