[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 ...
随机推荐
- doGet() throws NamingException报错
做一个通过JNDI查找资源的小练习,Context = new InitialContext(),发现NamingException异常,eclipse编辑器只有catch的提示,没有throws的提 ...
- Jenkins重启 在Windows GUI上
To restart Jenkins manually, you can use either of the following commands: (jenkins_url)/safeRestart ...
- 2015-2016 ACM-ICPC Pacific Northwest Regional Contest (Div. 2)V - Gears
Problem V | limit 4 secondsGearsA set of gears is installed on the plane. You are given the center c ...
- js验证手机号,身份证,车牌号验证
js验证手机号 <input type="text" class="identificationno"> // 身份证号码为15位或者18位,15 ...
- Flask的配置文件 与 session
配置文件 flask中的配置文件是一个flask.config.Config对象(继承字典) 默认配置为: { 'DEBUG': get_debug_flag(default=False), 是否开启 ...
- 响应在此上下文中不可用 asp.net
(一)实例1: 在asp.net程序中添加了一个 类.cs 如下 using System; using System.Collections; using System.ComponentModel ...
- CodeForces 124C Prime Permutation (数论+贪心)
题意:给定一个字符串,问你能不能通过重排,使得任意一个素数p <= 字符串长度n,并且 任意的 i <= 长度n/素数p,满足s[p] == s[p*i]. 析:很容易能够看出来,只要是某 ...
- CSMA/CA协议
802.11中采用CSMA/CA协议来规定多个工作节点共用信道的问题. CSMA/CA的全称是Carrier sense multiple access with collision avoidanc ...
- Android 性能优化(19)*代码优化11条技巧:Performance Tips
Performance Tips 1.In this document Avoid Creating Unnecessary Objects 避免多余的对象 Prefer Static Over Vi ...
- Spring抽象JDBC,使用JdbcTemplate
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp ...