7 Serialize and Deserialize Binary Tree 序列化及反序列化二叉树
原题网址:http://www.lintcode.com/zh-cn/problem/serialize-and-deserialize-binary-tree/#
设计一个算法,并编写代码来序列化和反序列化二叉树。将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉树被称为“反序列化”。
如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将二叉树序列化为一个字符串,并且可以将字符串反序列化为原来的树结构。
注意事项
There is no limit of how you deserialize or serialize a binary tree, LintCode will take your output of serialize
as the input of deserialize
, it won't check the result of serialize.
给出一个测试数据样例, 二叉树{3,9,20,#,#,15,7}
,表示如下的树结构:
3
/ \
9 20
/ \
15 7
我们的数据是进行BFS遍历得到的。当你测试结果wrong answer时,你可以作为输入调试你的代码。
你可以采用其他的方法进行序列化和反序列化。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/ class Solution {
public:
/**
* This method will be invoked first, you should design your own algorithm
* to serialize a binary tree which denote by a root node to a string which
* can be easily deserialized by your own "deserialize" method later.
*/
string serialize(TreeNode * root) { // write your code here
if (root==NULL)
{
return "";//return NULL出错;
}
string result;
//result=result+to_string(root->val);
result=result+int2str(root->val); queue<TreeNode *> level;
level.push(root->left);
level.push(root->right); while(!level.empty())
{
TreeNode *temp=level.front();
level.pop();
if (temp!=NULL)
{
//result=result+","+to_string(temp->val);
result=result+","+int2str(temp->val);
level.push(temp->left);
level.push(temp->right);
}
else
{
result=result+","+"#";
}
} int size=result.size();
int id=size-;
while(id>&&(result[id]=='#'||result[id]==','))
{
id--;
}
result.resize(id+); return result;
} /**
* 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.
*/
TreeNode * deserialize(string &data) {
// write your code here
if (data.empty())
{
return NULL;
} int size=data.size();
int i=;
int ro=;//根节点数值;
while(data[i]!=','&&i<size)
{
char tm=data[i];
ro=ro*+tm-'';
i++;
}
TreeNode * root=new TreeNode(ro); queue<TreeNode *> level;
TreeNode *index=root;
bool isLeft=true; for (;i<size;i++)
{
if (data[i]==',')
{
continue;
}
else if (data[i]=='#')
{
if (isLeft)
{
//index->left=NULL;
isLeft=false;
}
else
{
//index->right=NULL;
if (!level.empty())
{
index=level.front();
level.pop();
}
isLeft=true;
}
}
else
{
int val=;
while(i<size&&data[i]!=',') //注意不能写成data[i]!=','&&i<size,因为下标可能超出范围;
{
char temp=data[i];
val=val*+temp-'';
i++;
} TreeNode * tempNode=new TreeNode(val);
level.push(tempNode);
if (isLeft)
{
index->left=tempNode;
isLeft=false;
}
else
{
index->right=tempNode;
if (!level.empty())
{
index=level.front();
level.pop();
}
isLeft=true;
}
}
}
return root;
} string int2str(int &i)
{
string str;
stringstream stream;
stream<<i;
str=stream.str();//stream>>str;
return str;
} };
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/ class Solution {
public:
/**
* This method will be invoked first, you should design your own algorithm
* to serialize a binary tree which denote by a root node to a string which
* can be easily deserialized by your own "deserialize" method later.
*/
string serialize(TreeNode * root) { // write your code here
if (root==NULL)
{
return "";
}
string result;
//result=result+to_string(root->val);
result=result+int2str(root->val); queue<TreeNode *> level;
if (root->left==NULL&&root->right!=NULL)
{
level.push(root);
level.push(root->right);
}
else if (root->left!=NULL&&root->right==NULL)
{
level.push(root->left);
level.push(root);
}
else if (root->left!=NULL&&root->right!=NULL)
{
level.push(root->left);
level.push(root->right);
} while(!level.empty())
{
TreeNode *temp=level.front();
level.pop();
if (temp!=root)
{
//result=result+","+to_string(temp->val);
result=result+","+int2str(temp->val); if (temp->left!=NULL&&temp->right!=NULL)
{
level.push(temp->left);
level.push(temp->right);
}
else if (temp->left==NULL&&temp->right!=NULL)
{
level.push(root);
level.push(temp->right);
}
else if (temp->left!=NULL&&temp->right==NULL)
{
level.push(temp->left);
level.push(root);
}
else
{
level.push(root);
level.push(root);
}
}
else
{
result=result+","+"#";
}
} int size=result.size();
int id=size-;
while(id>&&(result[id]=='#'||result[id]==','))
{
id--;
}
result.resize(id+); return result;
} /**
* 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.
*/
TreeNode * deserialize(string &data) {
// write your code here
if (data.empty())
{
return NULL;
} int size=data.size();
int i=;
int ro=;//根节点数值;
while(data[i]!=','&&i<size)
{
char tm=data[i];
ro=ro*+tm-'';
i++;
}
TreeNode * root=new TreeNode(ro); queue<TreeNode *> level;
TreeNode *index=root;
bool isLeft=true; for (;i<size;i++)
{
if (data[i]==',')
{
continue;
}
else if (data[i]=='#')
{
if (isLeft)
{
//index->left=NULL;
isLeft=false;
}
else
{
//index->right=NULL;
if (!level.empty())
{
index=level.front();
level.pop();
}
isLeft=true;
}
}
else
{
int val=;
while(i<size&&data[i]!=',') //注意不能写成data[i]!=','&&i<size,因为下标可能超出范围;
{
char temp=data[i];
val=val*+temp-'';
i++;
} TreeNode * tempNode=new TreeNode(val);
level.push(tempNode);
if (isLeft)
{
index->left=tempNode;
isLeft=false;
}
else
{
index->right=tempNode;
if (!level.empty())
{
index=level.front();
level.pop();
}
isLeft=true;
}
}
}
return root;
} string int2str(int &i)
{
string str;
stringstream stream;
stream<<i;
str=stream.str();//stream>>str;
return str;
} };
7 Serialize and Deserialize Binary Tree 序列化及反序列化二叉树的更多相关文章
- [leetcode]297. Serialize and Deserialize Binary Tree 序列化与反序列化二叉树
Serialization is the process of converting a data structure or object into a sequence of bits so tha ...
- [leetcode]428. Serialize and Deserialize N-ary Tree序列化与反序列化N叉树
Serialization is the process of converting a data structure or object into a sequence of bits so tha ...
- [LintCode] Serialize and Deserialize Binary Tree(二叉树的序列化和反序列化)
描述 设计一个算法,并编写代码来序列化和反序列化二叉树.将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉树被称为“反序列化”. 如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将二叉 ...
- 【LeetCode】297. Serialize and Deserialize Binary Tree 解题报告(Python)
[LeetCode]297. Serialize and Deserialize Binary Tree 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode ...
- [LeetCode] Serialize and Deserialize Binary Tree
Serialize and Deserialize Binary Tree Serialization is the process of converting a data structure or ...
- LC 297 Serialize and Deserialize Binary Tree
问题: Serialize and Deserialize Binary Tree 描述: Serialization is the process of converting a data stru ...
- LeetCode——Serialize and Deserialize Binary Tree
Description: Serialization is the process of converting a data structure or object into a sequence o ...
- LintCode 7.Serialize and Deserialize Binary Tree(含测试代码)
题目描述 设计一个算法,并编写代码来序列化和反序列化二叉树.将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉树被称为“反序列化”. 如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将 ...
- [LeetCode] Serialize and Deserialize Binary Tree 二叉树的序列化和去序列化
Serialization is the process of converting a data structure or object into a sequence of bits so tha ...
随机推荐
- Vmware Centos7 配置静态 ip 和 使宿主机和虚拟机互相 ping 通
NAT 方式1. 配置静态 ipVmware 安装 Centos7 可以参考 https://blog.csdn.net/guo_ridgepole/article/details/78973763 ...
- Python匹马行天下之初识python!
python的发展史 1989年,被称为龟叔的Guido在为ABC语言写插件时,产生了写一个简洁又实用的编程语言的想法,并开始着手编写.因为其喜欢Monty Python喜剧团,所以将其命名为pyth ...
- STM32---初学者用库函数好还是直接对寄存器操作比较好
引用:http://blog.csdn.net/u010349006/article/details/416 首先,两个都是C语言.从51过渡过来的话,就先说寄存器操作.每个MCU都有自己的寄存器,5 ...
- Flask-session用法
概念 flask-session是flask框架的session组件,由于原来flask内置session使用签名cookie保存,该组件则将支持session保存到多个地方,如: * redis:保 ...
- duboo注解使用详解
一.背景 随着互联网的发展,网站应用的规模不断扩大,常规的垂直应用架构已无法应对,分布式服务架构以及流动计算架构势在必行. 当越来越的的接口与实现类的增加后,duboo的xml配置会越来越多,为了防止 ...
- vba取局域网电脑共享文件夹下的Excel文件
Private Sub CommandButton1_Click() Dim xlapp1 As Excel.Application Dim xlbook1 As Excel.Workbo ...
- redis 体系结构
程序strings key-value 类型 ,value不仅是String,也可以是数字.使用strings 类型可以完全实现目前 Memcache 的功能,并且效率更高,还可以享受redis的 ...
- canvas填充规则,非零环绕
1.看一块区域是否填充 2.从这个区域拉一条直线 3,看和这条直线相交的轨迹 4.如果顺时针轨迹+1 5.如果逆时针轨迹-1 6.所有轨迹的值计算出来 7.如果是非0,那么填充 8.如果是0那么不填充
- 阿里云 Aliplayer高级功能介绍(二):缩略图
基本介绍 Aliplayer提供了缩略图的功能,让用户在拖动进度条之前知道视频的内容,用户能够得到很好的播放体验,缩略图是显示在Controlbar的上面,并且包含当前的时间,阿里云的媒体处理服务提供 ...
- BZOJ 1398: Vijos1382寻找主人 Necklace(最小表示法)
传送门 解题思路 最小表示法.首先对于判断是不是循环同构的串,直接扫一遍用哈希判即可.然后要输出字典序最小的就要用到最小表示法,首先可以把串复制一遍,这样的话就可以把串变成静态操作.如果对于两个位置\ ...