二叉树的序列化和反序列化
2015-09-01 20:56
393 查看
该题首先用先序遍历的思路把树转换(序列化)为字符串,这样在恢复的时候就可以根据字符串先序遍历的特点进行恢复(反序列化)。
string int2str(int intsrc){
stringstream ss;
ss << intsrc;
return ss.str();
}
//序列化代码,先序遍历的顺序进行序列化
string serialize(TreeNode *root) {
// write your code here
string sec;
if(root == nullptr){
sec += "# ";
}else{
sec += int2str(root -> val);
sec += " ";
sec += serialize(root -> left);
sec += serialize(root -> right);
}
return sec;
}
/**
* This method will be invoked second, the argument data is what exactly
* you serialized at method "serialize", that means the data is not given by
* system, it's given by your own serialize method. So the format of data is
* designed by yourself, and deserialize it here as you serialize it in
* "serialize" method.
*/
//找到序列中下一个树的节点字符串
int pos = 0;
string nextString(string src){
string result;
if(pos < src.length()){
if(src[pos] == ' '){
pos++;
}
while(src[pos] != ' '){
result += src[pos];
pos++;
}
return result;
}
}
int str2int(string strsrc){
return atoi(strsrc.c_str());
}
//反序列化,根据字串先序遍历的特点
TreeNode *deserialize(string data) {
// write your code here
string cur = nextString(data);
if(cur == "#"){
return nullptr;
}else{
TreeNode *root = new TreeNode(str2int(cur));
root -> left = deserialize(data);
root -> right = deserialize(data);
return root;
}
}
string int2str(int intsrc){
stringstream ss;
ss << intsrc;
return ss.str();
}
//序列化代码,先序遍历的顺序进行序列化
string serialize(TreeNode *root) {
// write your code here
string sec;
if(root == nullptr){
sec += "# ";
}else{
sec += int2str(root -> val);
sec += " ";
sec += serialize(root -> left);
sec += serialize(root -> right);
}
return sec;
}
/**
* This method will be invoked second, the argument data is what exactly
* you serialized at method "serialize", that means the data is not given by
* system, it's given by your own serialize method. So the format of data is
* designed by yourself, and deserialize it here as you serialize it in
* "serialize" method.
*/
//找到序列中下一个树的节点字符串
int pos = 0;
string nextString(string src){
string result;
if(pos < src.length()){
if(src[pos] == ' '){
pos++;
}
while(src[pos] != ' '){
result += src[pos];
pos++;
}
return result;
}
}
int str2int(string strsrc){
return atoi(strsrc.c_str());
}
//反序列化,根据字串先序遍历的特点
TreeNode *deserialize(string data) {
// write your code here
string cur = nextString(data);
if(cur == "#"){
return nullptr;
}else{
TreeNode *root = new TreeNode(str2int(cur));
root -> left = deserialize(data);
root -> right = deserialize(data);
return root;
}
}
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- android 代码实现控件之间的间距
- [Android]在代码里运行另一个程序的方法
- 关于指针的一些事情
- AVL树-自平衡二叉查找树(Java实现)
- 肯特·贝克:改变人生的代码整理魔法
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- 网页恶意代码的预防
- 高手写的Tracer-Flash代码调试类代码下载
- CSS代码缩写技巧
- 非主流Q-zOne代码代码搜集第1/2页
- CreateWeb.vbs 代码
- Lua中调用C++函数示例
- Lua中编译执行代码相关的函数详解
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- 更有效率的css代码编写第1/3页
- 代码中到底应不应当写注释?