[Algorithm] 7. Serialize and Deserialize Binary Tree
Description
Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a file is called 'serialization' and reading back from the file to reconstruct the exact same binary tree is 'deserialization'.
Example
An example of testdata: Binary tree {3,9,20,#,#,15,7}, denote the following structure:
3
/ \
9 20
/ \
15 7
Our data serialization use bfs traversal. This is just for when you got wrong answer and want to debug the input.
You can use other method to do serializaiton and deserialization.
Solution
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/ class Solution {
private:
void serializeBTree(TreeNode* node, string& output){
if(node != NULL){
output = output+to_string(node->val)+' ';
serializeBTree(node->left, output);
serializeBTree(node->right, output);
}else{
output+="# ";
}
} TreeNode* deserializeBTree(string& data){
if(data.length() == ) return NULL; // Get the first string which is divided with space character.
int pos = data.find(' ');
char *str = new char[pos];
data.copy(str, pos, );
data.erase(,pos+);
if(str[] == '#') return NULL; TreeNode *root = new TreeNode(atoi(str));
if(str) delete str; root->left = deserializeBTree(data);
root->right = deserializeBTree(data); return root;
}
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) {
// Serialize the tree in priority arrangement.
string output;
serializeBTree(root, output);
return output;
} /**
* 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) {
// Deserialize the tree in priority arrangement.
TreeNode *root = NULL;
root = deserializeBTree(data);
return root;
}
};
Tips
This solution makes use of the priority arrangement of the binary tree. Strings which are used for saving result are divided with a space character.
Alternative Solution
/**
* 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) {
// Serialize the tree in BFS(Breadth First Search).
std::ostringstream output;
std::queue<TreeNode*> que;
if(root) que.push(root); while(!que.empty()){ // If queue is not empty, process.
TreeNode *node = que.front();
if(node){
output << node->val << ' ';
que.push(node->left);
que.push(node->right);
}else{
output << "# ";
}
que.pop();
} return output.str();
} /**
* 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) {
// Deserialize the tree in priority arrangement.
if(data.empty()) return NULL;
std::queue<TreeNode*> que;
std::istringstream input(data);
string str;
input >> str;
TreeNode *root = new TreeNode(stoi(str));
que.push(root); while(!que.empty()){
TreeNode* node = que.front(); que.pop();
if(!(input>>str)) break;
if(str != "#"){
node->left = new TreeNode(stoi(str));
que.push(node->left);
} if(!(input>>str)) break;
if(str != "#"){
node->right = new TreeNode(stoi(str));
que.push(node->right);
}
} return root;
}
};
Tips
This alternative solution we can use is through BFS method. We make use of the stream string library to process the storage of the binary tree.
[Algorithm] 7. Serialize and Deserialize Binary Tree的更多相关文章
- [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】297. Serialize and Deserialize Binary Tree 解题报告(Python)
[LeetCode]297. Serialize and Deserialize Binary Tree 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode ...
- [LintCode] 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 ...
- LeetCode——Serialize and Deserialize Binary Tree
Description: Serialization is the process of converting a data structure or object into a sequence o ...
- 297. Serialize and Deserialize Binary Tree
题目: Serialization is the process of converting a data structure or object into a sequence of bits so ...
- LeetCode OJ 297. Serialize and Deserialize Binary Tree
Serialization is the process of converting a data structure or object into a sequence of bits so tha ...
- [Java]LeetCode297. 二叉树的序列化与反序列化 | Serialize and Deserialize Binary Tree
Serialization is the process of converting a data structure or object into a sequence of bits so tha ...
随机推荐
- [RK3288][Android6.0] 音频调试方法小结【转】
本文转载自:http://blog.csdn.net/kris_fei/article/details/70053135 Platform: ROCKCHIPOS: Android 6.0Kernel ...
- Web 设计与开发者必须知道的 15 个站点
新闻来源:catswhocode.com公司博客整整一个月没有更新了,最近一段时间,全公司都忙于两件事,为海尔集团做定制,为一个合作伙伴做 OEM,终于有了眉目.工作期间,常用到一些工具与帮助站点,今 ...
- Spring实战笔记
晚上看了这本书的前面几章,记录一下自己看到的要点. 全书分为四大部分,Spring核心,web,后台相关,与其它框架集成.今天主要看了第一部分. Spring最根本的使命是简化Java开发,全方位的简 ...
- HTTP方式播放FLV/mp4 :nginx+Yamdi/MP4BOX
[导语]chrome浏览器确实很强,直接支持MP4拖动播放,对于其他播放器,可以使用以下方法来支持拖动播放.拖动的关键在于生成关键帧等元数据信息,便于服务器和播放器支持拖动. 另外,nginx web ...
- navicat导入.sql文件出错2006-MySQLserver has gone away
方式一(验证无误): 找到mysql安装目录下的my.ini配置文件,加入以下代码: max_allowed_packet=500M wait_timeout=288000 interactive_t ...
- 【145】◀▶ .NET Framework类库索引
C#编程基础: A1 ………… 基础A2 ………… using 关键字A3 ………… as 关键字A4 ………… is 关键字A5 ………… switch 关键字A6 ………… return 语句关键 ...
- JSP页面结构
1.表达式格式(experssion):<%=value %>//用来在页面中调用java表达式,从而得到返回值 <%=new java.util.Date();%> 2.小脚 ...
- C++中的常量(一) const限定符
最近在重新看<<C++ Primer>>,第一遍的时候const和constexpr看得并不太懂,这次又有了些更新的理解,当然可能仍然有许多不对的地方... 首先,const限 ...
- P4576 [CQOI2013]棋盘游戏
传送门 很显然,除非白子和黑子相邻,否则必然是黑子获胜虽然我并没有看出来 那么现在对黑子来说它要尽可能快的赢,对白子它要多苟一会儿 然后就是这个叫做对抗搜索的东西了 //minamoto #inclu ...
- PostgreSQL逻辑复制之pglogical篇
PostgreSQL逻辑复制之slony篇 一.pglogical介绍 pglogical 是 PostgreSQL 的拓展模块, 为 PostgreSQL 数据库提供了逻辑流复制发布和订阅的功能. ...