[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, ...
随机推荐
- HTTP长连接短连接
一.什么是长连接 HTTP1.1规定了默认保持长连接(HTTP persistent connection ,也有翻译为持久连接),数据传输完成了保持TCP连接不断开(不发RST包.不四次握手),等待 ...
- MVC中的_viewstart.cshtml(没有设置Layout却引用了布局)
今天Home视图中新增了一个视图,因为不需要设置Layout就没与管他,但是运行起来一看,自动引用了布局,分析了半天 也没看出是哪的错误? 后来尝试着在area中增加了一个同样的视图就没有问题,比较这 ...
- google推出的SwipeRefreshLayout下拉刷新用法
使用如下: 1.先下载android-support-v4.jar最新版本,之前的版本是没有SwipeRefreshLayout下拉刷新控件的,如果已经更新,此步骤可省略. 2.在xml文件中引用an ...
- Unity3D Optimizing Graphics Performance for iOS
原地址:http://blog.sina.com.cn/s/blog_72b936d801013ptr.html icense Comparisons http://unity3d.com/unity ...
- 通过IIS调试ASP.NET项目
当我们使用Visual Studio调试的时候,通常我们会选择VS自带的ASP.NET Developerment Server(也是默认选项),当第一次调试的时候(按F5或Ctrl+F5不调试直接打 ...
- navicat连接oracle报错ORA-12737: Instant Client Light: unsupported server character set CHS16GBK”
原文如下http://blog.163.com/cp7618@yeah/blog/static/7023477720142154449893/?COLLCC=1318255100& 这个工具可 ...
- HDOJ 1026 dfs路径保存
#include<cstdio> #include<cstring> #include<cmath> ][]; #define inf 0xffffff int n ...
- webservice 协议
Web Service使用的是 SOAP (Simple Object Access Protocol)协议soap协议只是用来封装消息用的.封装后的消息你可以通过各种已有的协 ...
- eclipse 启动后,啥也不干,就一直在loading descriptor for XXX (XXX为工程名),,其他什么操作都不能操作。 如下图所示,保存文件也无法保存。 这个怎么办?一年好几天,什么都干不了!!!!!
解决办法: 解决办法是 断一下网就好了
- C++ traits
[本文链接] http://www.cnblogs.com/hellogiser/p/cplusplus-traits.html [分析] 什么是traits?其实它并不是一个新的概念,上个世纪90年 ...