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. XSS的DOS攻击之 server limit dos

    墨西哥同学周末很郁闷的在宾馆上网,发现youtube被ban了,于是写个了tool解决这个问题.顺带想到了一种利用 google 统计的漏洞,写在这里了 http://sirdarckcat.blog ...

  2. Unity3D开发之NGUI点击事件穿透响应处理

    http://www.xuebuyuan.com/1936292.html 在使用NGUI 开发2D项目的时候,发现了一个问题,就是如果点出一个菜单,然后点击菜单上面的按钮的时候就会使得按钮下面的物品 ...

  3. 教程Xcode 4下编译发布与提交App到AppStore

    地址:http://www.cocoachina.com/bbs/simple/?t55825.html 教程Xcode 4下编译发布与提交App到AppStore 先说一下这个是我在网上看到的一个帖 ...

  4. IOS 入门开发之创建标题栏UINavigationBar的使用(二)

    IOS 入门开发之创建标题栏UINavigationBar的使用 http://xys289187120.blog.51cto.com/3361352/685746     IOS 开发有关界面的东西 ...

  5. ruby实时查看日志

    (文章是从我的个人主页上粘贴过来的, 大家也可以访问我的主页 www.iwangzheng.com) 在调试代码的时候,把日志文件打开,边操作边调试能很快帮助我们发现系统中存在的问题. $tail r ...

  6. 当前标识(IIS APPPOOL\DefaultWebSite)没有对“C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files“的写访问权限

    将C#写的webservice发布到IIS后,通过浏览器访问测试,出现如下错误: 根据提示:对Tempory ASP.NET Files没有写访问权限,在资源管理其中定位到这个地址,发现没有这个文件夹 ...

  7. 解决android:theme="@android:style/Theme.NoDisplay" 加入这句话后程序不能运行

    原因: 原来用的是ActionBarActivity,继承自 ActionBarActivity的类必须指定固定的集中Theme风格,而这些 Theme 风格是需要导入V7中的 appcompat L ...

  8. 使用豆瓣的pypi源

    配置文件位置: 1.linux ~/.pip/pip.conf 2.windows %HOME%\pip\pip.ini 配置文件内容:[global] index-url = http://pypi ...

  9. 【Python】python 普通继承方式和super继承方式

    Python中对象方法的定义很怪异,第一个参数一般都命名为self(相当于其它语言的this),用于传递对象本身,而在调用的时候则不必显式传递,系统会自动传递.举一个很常见的例子:>>&g ...

  10. 【leetcode】Sudoku Solver

    Sudoku Solver Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are i ...