原题网址: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. Maven精选系列--classifier元素妙用

    首先来看这么一个依赖 <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json- ...

  2. rmReport 自适应行高(自动行高)

    这个问题 1.先中主项数据--属性--stretched(伸展):true 选中主项数据中的所有列--属性--其他属性--自动折行 --伸展

  3. 关于webpack一些路径

    好多新手对webpack中的路径一直感到迷茫,其实再学习webpack之前都应该去了解下nodejs的内容, 以为webpack就是个nodejs项目,所以里面涉及到的路径都是nodejs里面的写法 ...

  4. js 本地预览图片和得到图片实际大小

    //填充预览图片 function adpter(file, upfile) { var imgName = new Date().getTime() + file.name.substr(file. ...

  5. webgoat的构建

    如何打开webgoat 1.ctrl+r  打开命令 2.cmd 打开命令编辑器 3.我的webgoat保存在E:/安全软件/webgoat-container-7.0.1-war-exec下 4.在 ...

  6. win10安装mysql__艰难的心路历程

    俺是新系统,嘿嘿嘿 首先,把下载好的压缩包解压到安装目录中,哪个盘可以. 第二,先创建my.ini文件,不然待会忘了.在文件中添加以下内容: [mysqld] port = basedir=C:\Wi ...

  7. leetcode-220-存在重复元素③*

    题目描述: 方法一:二叉搜索树+滑动窗口 方法二:桶排序 O(N) class Solution: def containsNearbyAlmostDuplicate(self, nums: List ...

  8. [JZOJ6340] 【NOIP2019模拟2019.9.4】B

    题目 题目大意 给你个非负整数数列\(a\),每次等概率选择大于零的\(a_i\),使其减\(1\). 问\(a_1\)被减到\(0\)的时候期望经过多少次操作. 思考历程 对于这题的暴力做法,显然可 ...

  9. [SNOI 2017] 炸弹

    题目描述: 给定炸弹和爆炸范围,求对于每个炸弹连锁爆炸的炸弹总和对\(1e9+7\)取膜 思路: 为啥都是线段树+TS+tarjan呢? 实在是搞不懂~~ 线性\(O(n)\)递推即可. #inclu ...

  10. http://ajax.open-open.com/ ajax开源家园

    http://ajax.open-open.com/ 本站为广大OPEN爱好者搭建了一个OPEN家园,大家可以方便快捷地发布日志.上传照片,分享生活中的精彩瞬间:与好友一起玩转游戏,增加好友感情:创建 ...