原题网址: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.

您在真实的面试中是否遇到过这个题?

Yes
样例

给出一个测试数据样例, 二叉树{3,9,20,#,#,15,7},表示如下的树结构:

  3
/ \
9 20
/ \
15 7

我们的数据是进行BFS遍历得到的。当你测试结果wrong answer时,你可以作为输入调试你的代码。

你可以采用其他的方法进行序列化和反序列化。

标签

 
思路:序列化二叉树时用广度优先搜素的方法,设置一个队列保存节点,依次遍历。因为空节点无法插入队列,所以用root代替空节点,这样判断当前节点是否为root就可以判断是有效节点还是空节点了。
注意,该程序结束时字符串尾部会插入多余的‘#’和‘,’,要将这些无效字符删掉。
 
更新:又测试了下发现NULL可以插入指针队列,emmm……
 
 
反序列化:依旧是利用队列的先入先出特性,因为要判断新建立的节点是左节点还是右节点,所以再设置一个bool类型的判断标志。
首先建立根节点,然后遍历字符串,如果当前字符为‘,’就continue;
如果为‘#’就判断新建立的是左节点还是右节点,如果是右节点代表其根节点已经全部挂载完成,此时需要队列出队,在下一个节点上继续挂载,同时标志反转;
否则,当前节点为有效数值,首先将这些字符转换成int型数据,然后new出一个二叉树节点,判断挂载在左侧还是右侧,然后标志反转,若是右侧,队列再出队。
 
 
AC代码:
注意空字符串要返回""而不是NULL……
以及,int转string可以用to_string(),但我测试代码时用的VS2010,还不能支持这个函数,所以自己定义了一个。
 
/**
* 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;
} };

参考:C++中int、string等常见类型转换

C++中int与string的相互转换

C++ STL--queue 的使用方法

其他参考:
 
 
 

7 Serialize and Deserialize Binary Tree 序列化及反序列化二叉树的更多相关文章

  1. [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 ...

  2. [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 ...

  3. [LintCode] Serialize and Deserialize Binary Tree(二叉树的序列化和反序列化)

    描述 设计一个算法,并编写代码来序列化和反序列化二叉树.将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉树被称为“反序列化”. 如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将二叉 ...

  4. 【LeetCode】297. Serialize and Deserialize Binary Tree 解题报告(Python)

    [LeetCode]297. Serialize and Deserialize Binary Tree 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode ...

  5. [LeetCode] Serialize and Deserialize Binary Tree

    Serialize and Deserialize Binary Tree Serialization is the process of converting a data structure or ...

  6. LC 297 Serialize and Deserialize Binary Tree

    问题: Serialize and Deserialize Binary Tree 描述: Serialization is the process of converting a data stru ...

  7. LeetCode——Serialize and Deserialize Binary Tree

    Description: Serialization is the process of converting a data structure or object into a sequence o ...

  8. LintCode 7.Serialize and Deserialize Binary Tree(含测试代码)

    题目描述 设计一个算法,并编写代码来序列化和反序列化二叉树.将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉树被称为“反序列化”. 如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将 ...

  9. [LeetCode] Serialize and Deserialize Binary Tree 二叉树的序列化和去序列化

    Serialization is the process of converting a data structure or object into a sequence of bits so tha ...

随机推荐

  1. Vmware Centos7 配置静态 ip 和 使宿主机和虚拟机互相 ping 通

    NAT 方式1. 配置静态 ipVmware 安装 Centos7 可以参考 https://blog.csdn.net/guo_ridgepole/article/details/78973763 ...

  2. Python匹马行天下之初识python!

    python的发展史 1989年,被称为龟叔的Guido在为ABC语言写插件时,产生了写一个简洁又实用的编程语言的想法,并开始着手编写.因为其喜欢Monty Python喜剧团,所以将其命名为pyth ...

  3. STM32---初学者用库函数好还是直接对寄存器操作比较好

    引用:http://blog.csdn.net/u010349006/article/details/416 首先,两个都是C语言.从51过渡过来的话,就先说寄存器操作.每个MCU都有自己的寄存器,5 ...

  4. Flask-session用法

    概念 flask-session是flask框架的session组件,由于原来flask内置session使用签名cookie保存,该组件则将支持session保存到多个地方,如: * redis:保 ...

  5. duboo注解使用详解

    一.背景 随着互联网的发展,网站应用的规模不断扩大,常规的垂直应用架构已无法应对,分布式服务架构以及流动计算架构势在必行. 当越来越的的接口与实现类的增加后,duboo的xml配置会越来越多,为了防止 ...

  6. vba取局域网电脑共享文件夹下的Excel文件

    Private Sub CommandButton1_Click()    Dim xlapp1 As Excel.Application    Dim xlbook1 As Excel.Workbo ...

  7. redis 体系结构

    程序strings   key-value 类型 ,value不仅是String,也可以是数字.使用strings 类型可以完全实现目前 Memcache 的功能,并且效率更高,还可以享受redis的 ...

  8. canvas填充规则,非零环绕

    1.看一块区域是否填充 2.从这个区域拉一条直线 3,看和这条直线相交的轨迹 4.如果顺时针轨迹+1 5.如果逆时针轨迹-1 6.所有轨迹的值计算出来 7.如果是非0,那么填充 8.如果是0那么不填充

  9. 阿里云 Aliplayer高级功能介绍(二):缩略图

    基本介绍 Aliplayer提供了缩略图的功能,让用户在拖动进度条之前知道视频的内容,用户能够得到很好的播放体验,缩略图是显示在Controlbar的上面,并且包含当前的时间,阿里云的媒体处理服务提供 ...

  10. BZOJ 1398: Vijos1382寻找主人 Necklace(最小表示法)

    传送门 解题思路 最小表示法.首先对于判断是不是循环同构的串,直接扫一遍用哈希判即可.然后要输出字典序最小的就要用到最小表示法,首先可以把串复制一遍,这样的话就可以把串变成静态操作.如果对于两个位置\ ...