[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, ...
随机推荐
- HDU 4883 TIANKENG’s restaurant
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4883 解题报告:一家餐馆一天中有n波客人来吃饭,第 i 波 k 客人到达的时间是 s ,离开时的时间 ...
- basic use of sidekiq
参考页面 https://github.com/mperham/sidekiq https://github.com/mperham/sidekiq/wiki/Getting-Started 强烈推荐 ...
- 对大一新生开始学习C语言课程谈几点看法
大家好,首先祝贺大家进入了大学,迈入了大学的校门,也意味着开始了新的征程,希望大家能够有一个美好的大学四年. 先做下自我介绍,我叫李帅阳,(大家可以称呼我 李老师,或是班助,或是...)这是在邹欣老师 ...
- BZOJ2904
找了一个晚上的资料,拼凑出来这么一个东西: 1) 如果是完全平方数返回12) 如果可以表示成形如$x^2+y^2$的形式输出2.这要求该数质因数分解后形如$4k+3$的质因数次数都是偶数.3) 如果该 ...
- C语言指针总结
C语言中的精华是什么,答曰指针,这也是C语言中唯一的难点. C是对底层操作非常方便的语言,而底层操作中用到最多的就是指针,以后从事嵌入式开发的朋友们,指针将陪伴我们终身. 本文将从八个常见的方面来透视 ...
- TCP中 recv和sendf函数
recv和send函数: #include<sys/socket.h> ssize_t recv(int sockfd, void *buff, size_t nbytes, int fl ...
- 【leetcode】Implement strStr()
Implement strStr() Implement strStr(). Returns the index of the first occurrence of needle in haysta ...
- 44. log(n)求a的n次方[power(a,n)]
[题目] 实现函数double Power(double base, int exponent),求base的exponent次方,不需要考虑溢出. [分析] 这是一道看起来很简单的问题,很容易写出如 ...
- gpart 使用笔记
需求 将260G 的/home 分区拆成/home与/data,原/home分区上的数据不用保留,新/home为100G,剩余空间给/data gpart过程 1.df 结果: # Device ...
- HTML页面表单输入框去掉鼠标选中后边框变色的效果
标题说的有些含糊,实在不知道怎么描述了,就简单说一下吧,一个最简单的表单,代码如下,没有任何样式和名字, <!DOCTYPE html> <html> <head> ...