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. Windows10、ARM开发板、VMware虚拟机同时连接Internet

    前段时间有人遇到一些网络连接问题,让我帮忙处理,他想让ARM开发板连接外网,可以连接网络数据库,同时保证自己的电脑可以上网. 本来说直接可以连接一个路由器,分配一个内网IP给ARM就可以了,但是当时那 ...

  2. Interval 计时器

    语法: setInterval(代码,交互时间); 在执行时,从载入页面后每隔指定的时间执行代码. clearInterval( setInterval() 返回的 ID 值 ): 取消计时器 < ...

  3. Coolite Toolkit介绍

    Coolite Toolkit非常棒的控件   Coolite Toolkit介绍 Coolite Toolkit 是一个支持ASP.NET AJAX的Web控件. Coolite Toolkit是基 ...

  4. 51Nod 1967 路径定向 —— 欧拉回路

    题目:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1967 显然是欧拉回路问题,度数为奇数的点之间连边,跑欧拉回路就可以 ...

  5. 通过CSS控制页面中的内容垂直居中的方法

    方法一:通过行高(line-height)定位 line-height通常是用于调节一段文字的行与行之间的距离,或者说两行文字之间的距离,如果行高是500px,那么每一行中的文字距离本行的顶部就是25 ...

  6. log4j日志基本配置

    Log4j有三个主要的组件:Loggers(记录器),Appenders (输出源)和Layouts(布局).这里可简单理解为日志类别,日志要输出的地方和日志以何种形式输出.综合使用这三个组件可以轻松 ...

  7. bzoj 1833: [ZJOI2010]count 数字计数【数位dp】

    非典型数位dp 先预处理出f[i][j][k]表示从后往前第i位为j时k的个数,然后把答案转换为ans(r)-ans(l-1),用预处理出的f数组dp出f即可(可能也不是dp吧--) #include ...

  8. 10.17NOIP模拟赛

    #include<iostream> #include<cstdio> #include<cstring> #define N 1001 using namespa ...

  9. Linux学习之02_Linuxd的文件权限与目录配置

    这里一些基本介绍就不介绍了,还是来介绍一下相关的命令 这一节重要的命令有这些: chgrp chown chmod 1.改变文件属性和权限 chgrp----改变文件所属用户组 chown----改变 ...

  10. 基于ASP.Net Core开发一套通用后台框架记录-(数据库设计(权限模块))

    写在前面 本系列博客是本人在学习的过程中搭建学习的记录,如果对你有所帮助那再好不过.如果您有发现错误,请告知我,我会第一时间修改. 前期我不会公开源码,我想是一点点敲代码,不然复制.粘贴那就没意思了. ...