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

There is no limit of how you deserialize or serialize a binary tree, you only need to make sure you can serialize a binary tree to a string and deserialize this string to the original structure.

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.

基本思路:

利用queue层次遍历整棵树。对每次出队的结点,如果它是一个空结点,则再string后加入标记‘#’。如果它不是一个空节点,则把它的val加入到string中(如果string当前以一个非空结点结尾,我们加入一个’_'间隔),然后把这个结点的两个孩子入队(空节点也入队一次)。

/**
* 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:
static const char nullNode = '#';
static const char nodeSpliter = '_'; inline string int2str(int val){
stringstream strStream;
strStream << val;
return strStream.str();
} inline int str2int(string str){
return atoi(str.c_str());
} inline void encode(string &str, TreeNode *node){
if(node == NULL) {
str += nullNode;
return;
} if(str == "" || str.back() == nullNode)
str += int2str(node->val);
else
str += nodeSpliter + int2str(node->val);
} vector<string> splitStr(string &str){
vector<string> result;
if(str == "") return result;
int start = , end = , n = str.size();
while(true){
while(start < n && str[start] == nodeSpliter) ++start;
if(start >= n) break; end = start + ;
if(str[start] != nullNode){
while(end < n && str[end] != nullNode && str[end] != nodeSpliter)
++end;
}
result.push_back(str.substr(start, end - start));
start = end;
}
return result;
} 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) {
if(root == NULL) return ""; string encodedStr = "";
queue<TreeNode*> nodeQueue;
nodeQueue.push(root); while(!nodeQueue.empty()){
TreeNode *cur = nodeQueue.front();
nodeQueue.pop();
encode(encodedStr, cur);
if(cur != NULL){
nodeQueue.push(cur->left);
nodeQueue.push(cur->right);
}
}
return encodedStr;
} /**
* 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) {
vector<string> splitRes = splitStr(data);
if(splitRes.size() == ) return NULL; TreeNode *root = new TreeNode(str2int(splitRes[]));
queue<TreeNode*> nodeQueue;
nodeQueue.push(root); for(int i = ;i < splitRes.size();i+=){
if(nodeQueue.empty()) return root;
TreeNode *curNode = nodeQueue.front();
nodeQueue.pop();
//left son
if(splitRes[i][] == nullNode){
curNode->left = NULL;
}else{
curNode->left = new TreeNode(str2int(splitRes[i]));
nodeQueue.push(curNode->left);
}
//right son
if(splitRes[i + ][] == nullNode){
curNode->right = NULL;
}else{
curNode->right = new TreeNode(str2int(splitRes[i + ]));
nodeQueue.push(curNode->right);
}
} return root;
}
};

[LintCode] Binary Tree Serialization的更多相关文章

  1. Lintcode: Binary Tree Serialization (Serialization and Deserialization Of Binary Tree)

    Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a ...

  2. [LintCode] Binary Tree Level Order Traversal(二叉树的层次遍历)

    描述 给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问) 样例 给一棵二叉树 {3,9,20,#,#,15,7} : 3 / \ 9 20 / \ 15 7 返回他的分层遍历结果: [ [3] ...

  3. [lintcode] Binary Tree Maximum Path Sum II

    Given a binary tree, find the maximum path sum from root. The path may end at any node in the tree a ...

  4. [LintCode] Binary Tree Paths 二叉树路径

    Given a binary tree, return all root-to-leaf paths.Example Given the following binary tree: 1 /   \2 ...

  5. LintCode Binary Tree Maximum Path Sum

    Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. ...

  6. LintCode Binary Tree Inorder Traversal

    Binary Tree Inorder Traversal Given a binary tree, return the inorder traversal of its nodes' values ...

  7. LintCode Binary Tree Paths

    Binary Tree Paths Given a binary tree, return all root-to-leaf paths. Given the following binary tre ...

  8. LintCode Binary Tree Preorder Traversal

    Given a binary tree, return the preorder traversal of its nodes' values. Given: 1 / \ 2 3 / \ 4 5 re ...

  9. LintCode Binary Tree Level Order Traversal

    Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, ...

随机推荐

  1. MapReduce中TextInputFormat分片和读取分片数据源码级分析

    InputFormat主要用于描述输入数据的格式(我们只分析新API,即org.apache.hadoop.mapreduce.lib.input.InputFormat),提供以下两个功能: (1) ...

  2. ReactiveCocoa 和 MVVM 入门 (转)

    翻译自ReactiveCocoa and MVVM, an Introduction. 文中引用的 Gist 可能无法显示.为了和谐社会, 请科学上网. MVC 任何一个正经开发过一阵子软件的人都熟悉 ...

  3. PHP数据访问

    <?php //作业:把INFO表查出来用表格显示 //1.造一个连接对象 $db = new MySQLi("localhost","root",&qu ...

  4. 百度图片爬虫-python版-如何爬取百度图片?

    上一篇我写了如何爬取百度网盘的爬虫,在这里还是重温一下,把链接附上: http://www.cnblogs.com/huangxie/p/5473273.html 这一篇我想写写如何爬取百度图片的爬虫 ...

  5. java笔试二

    16.同步和异步有何异同,在什么情况下分别使用他们?举例说明.如果数据将在线程间共享.例如正在写的数据以后可能被另一个线程读到,或者正在读的数据可能已经被另一个线程写过了,那么这些数据就是共享数据,必 ...

  6. PXE介绍(PXE+kickstart无人值守安装)

    PXE概念 PXE(Pre-boot Execution Environment,预启动执行环境)是由Intel公司开发的最新技术,工作于Client/Server的网络模式,支持工作站通过网络从远端 ...

  7. linux expect 简单讲解

    来自http://blog.csdn.net/winstary/archive/2009/08/08/4422156.aspx使用expect实现自动登录的脚本,网上有很多,可是都没有一个明白的说明, ...

  8. MySQL建立索引的注意事项

    对于大数据量的表格,尤其是百万行以上的数据表,一定要对其建立索引,否则查询速度极慢.(参考后面的测试结果)建立索引时需注意: MySQL的索引有两种:单列索引(即在某一列上建索引).多列组合索引(即在 ...

  9. linux下proc里关于磁盘性能的参数

    我 们在磁盘写操作持续繁忙的服务器上曾经碰到一个特殊的性能问题.每隔 30 秒,服务器就会遇到磁盘写活动高峰,导致请求处理延迟非常大(超过3秒).后来上网查了一下资料,通过调整内核参数,将写活动的高峰 ...

  10. 《ASP.NET1200例》统计网站访问量源代码

    void Application_Start(object sender, EventArgs e)     {        //在应用程序启动时运行的代码        int count=0;  ...