[LintCode] Binary Tree Serialization
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.
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的更多相关文章
- 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 ...
- [LintCode] Binary Tree Level Order Traversal(二叉树的层次遍历)
描述 给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问) 样例 给一棵二叉树 {3,9,20,#,#,15,7} : 3 / \ 9 20 / \ 15 7 返回他的分层遍历结果: [ [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 ...
- [LintCode] Binary Tree Paths 二叉树路径
Given a binary tree, return all root-to-leaf paths.Example Given the following binary tree: 1 / \2 ...
- 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. ...
- LintCode Binary Tree Inorder Traversal
Binary Tree Inorder Traversal Given a binary tree, return the inorder traversal of its nodes' values ...
- LintCode Binary Tree Paths
Binary Tree Paths Given a binary tree, return all root-to-leaf paths. Given the following binary tre ...
- LintCode Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes' values. Given: 1 / \ 2 3 / \ 4 5 re ...
- LintCode Binary Tree Level Order Traversal
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, ...
随机推荐
- [Effective JavaScript 笔记]第28条:不要信赖函数对象的toString方法
js函数有一个非凡的特性,即将其源代码重现为字符串的能力. (function(x){ return x+1 }).toString();//"function (x){ return x+ ...
- NGUI之scroll view制作,以及踩的坑总结
http://blog.csdn.net/monzart7an/article/details/23878505 链接: http://game.ceeger.com/forum/read.php?t ...
- Linux常用指令(持续更新)
(这些文章都是从我的个人主页上粘贴过来的,大家也可以访问我的主页 www.iwangzheng.com) PP真的是一位很有姿势的程序猿,有这样的邻居真好,榜样啊. pwd 当前路径 df -kh ...
- 在线调试和演示的前端开发工具------http://jsfiddle.net/
在线调试和演示的前端开发工具------http://jsfiddle.net/
- Word Pattern | & II
Word Pattern | Given a pattern and a string str, find if str follows the same pattern. Examples: pat ...
- Reverse Linked List | & ||
Reverse Linked List I Reverse a linked list. Example For linked list 1->2->3, the reversed lin ...
- fcitx-sogoupinyin下载地址和安装
伴随着Deepin 12.12 beta的发布,搜狗输入法也与我们见面了.在发布前几日Deepiner也通过各种途径向我们展示了搜狗Linux输入法,当然也掉足了胃口. 来自官方的截图: 当然令很多U ...
- 【Python爬虫】入门知识
爬虫基本知识 这阵子需要用爬虫做点事情,于是系统的学习了一下python爬虫,觉得还挺有意思的,比我想象中的能干更多的事情,这里记录下学习的经历. 网上有关爬虫的资料特别多,写的都挺复杂的,我这里不打 ...
- mysql 源码包 有的版本 可能没有 CMakeCache.txt
如果没有CMakeCache.txt 文件编译的时候会报错!!找不到CMakeCache.txt
- 第六步:Lucene查询索引
package cn.harmel.lucene; import java.io.IOException; import java.nio.file.Paths; import org.apache. ...