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的更多相关文章

  1. [LeetCode] Serialize and Deserialize Binary Tree

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

  2. LC 297 Serialize and Deserialize Binary Tree

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

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

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

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

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

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

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

  6. LeetCode——Serialize and Deserialize Binary Tree

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

  7. 297. Serialize and Deserialize Binary Tree

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

  8. 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 ...

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

随机推荐

  1. neo4j 张一鸣 8

    头条关注 粉丝关系 张一鸣 8

  2. 【Poj3126】【BNUOJ3245】Prime Path

    http://poj.org/problem?id=3126 https://www.bnuoj.com/v3/problem_show.php?pid=3245 题目鬼图 刚开始看到题目的图觉得这题 ...

  3. BZOJ_3175_[Tjoi2013]攻击装置_二分图匹配

    BZOJ_3175_[Tjoi2013]攻击装置_二分图匹配Description 给定一个01矩阵,其中你可以在0的位置放置攻击装置.每一个攻击装置(x,y)都可以按照“日”字攻击其周围的 8个位置 ...

  4. python-----列表生成式和列表生成器表达

    列表表达式: 程序一: 常规写法: L = [] for x in range(1, 11): L.append(x * x) print(L) #[1, 4, 9, 16, 25, 36, 49, ...

  5. SPI操作flash MX25L64读写数据

    STM32F10X SPI操作flash MX25L64读写数据 简单的一种应用,ARM芯片作为master,flash为slaver,实现单对单通信.ARM主控芯片STM32F103,flash芯片 ...

  6. java笔记线程方式1获取对象名称

    * 如何获取线程对象的名称呢? * public final String getName():获取线程的名称. * 如何设置线程对象的名称呢? * public final void setName ...

  7. SQL Server触发器创建、删除、修改、查看示例步骤

    一﹕ 触发器是一种特殊的存储过程﹐它不能被显式地调用﹐而是在往表中插入记录﹑更新记录或者删除记录时被自动地激活.所以触发器可以用来实现对表实施复杂的完整性约`束. 二﹕ SQL Server为每个触发 ...

  8. DFS/BFS(同余模) POJ 1426 Find The Multiple

    题目传送门 /* 题意:找出一个0和1组成的数字能整除n DFS:200的范围内不会爆long long,DFS水过~ */ /************************************ ...

  9. 13 继续C#中的方法,带返回值的方法介绍

    在这一个练习中,我们要使用带返回值的方法.如果一个方法带返回值,那么它的形式是这样的. 定义一个带返回值的C#方法 static 返回类型 方法名字 (参数类型 参数1的名字,参数类型 参数2的名字) ...

  10. 专题二:HTTP协议详解

    我们在用Asp.net技术开发Web应用程序后,当用户在浏览器输入一个网址时就是再向服务器发送一个HTTP请求,此时就使用了应用层的HTTP协议,在上一个专题我们简单介绍了网络协议的知识,主要是为了后 ...