[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 ...
随机推荐
- javascript总结02
1 如何打开和关闭一个新的窗口? 2 Window对象的哪个属性能返回上一个浏览页面? 3 一次或多次执行一段程序的函数是什么? 定时函数 4 如何查找并访问节点? 5 给表格新增行和单元格的方法分别 ...
- sql compare options
sql compare project's options Add object existence checks Use DROP and CREATE instead of ALTER Ignor ...
- Bing必应地图中国API-画线与添加多边形
Bing必应地图中国API-画线与添加多边形 2011-05-24 14:31:20| 分类: Bing&Google|字号 订阅 在必应地图上画线的功能应用也很广泛:显示从出发地到 ...
- JSP-Runoob:JSP 教程
ylbtech-JSP-Runoob:JSP 教程 1.返回顶部 1. JSP 教程 JSP 与 PHP.ASP.ASP.NET 等语言类似,运行在服务端的语言. JSP(全称Java Server ...
- libnids 中哈希表的建立
//hash.c #include <sys/types.h>#include <sys/time.h>#include <stdio.h>#include < ...
- springboot(二)整合mybatis,多数据源和事务管理
-- 1.整合mybatis -- 2.整合多数据源 -- 3. 整合事务 代码地址:https://github.com/showkawa/springBoot_2017/tree/master/ ...
- JavaScript--DOM删除节点removeChild()
删除节点removeChild() removeChild() 方法从子节点列表中删除某个节点.如删除成功,此方法可返回被删除的节点,如失败,则返回 NULL. 语法: nodeObject.remo ...
- ASP.NET 知识点总结(六)
1.传入某个属性的set方法的隐含参数的名称是什么?value,它的类型和属性所声名的类型相同. 2.如何在C#中实现继承? 在类名后加上一个冒号,再加上基类的名称.3.C#支持多重继承么? 类之间不 ...
- C#上机作业及代码Question2
第二题某文件名为"*.txt",其中*可能由若干个英文单词组成.将此文件名改为"*.dat",并且单词之间用下划线连接,例如: helloworld.txt,改 ...
- 折半枚举(双向搜索)poj27854 Values whose Sum is 0
4 Values whose Sum is 0 Time Limit: 15000MS Memory Limit: 228000K Total Submissions: 23757 Accep ...