LeetCode OJ:Serialize and Deserialize Binary Tree(对树序列化以及解序列化)

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

For example, you may serialize the following tree

    1
/ \
2 3
/ \
4 5

as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

这题实际上思路还是比较清晰的,遇见NULL的话那么存入一个#既可以了,解序列化的时候直接相应的处理#就可以了,代码如下:

 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Codec {
public: // Encodes a tree to a single string.
string serialize(TreeNode* root) {
queue<TreeNode *> q;
string str = "";
if(!root) return str;
stringstream ss;
ss << root->val;
str += ss.str();
q.push(root);
while(!q.empty()){
TreeNode * t = q.front();
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
if(t->left){
ss.str("");
ss << "," << t->left->val;
str += ss.str();
}else{
ss.str("");
ss << "," << "#";
str += ss.str();
} if(t->right){
ss.str("");
ss << "," << t->right->val;
str += ss.str();
}else{
ss.str("");
ss << "," << "#";
str += ss.str();
}
q.pop();
}
//删除末尾的#字符
for(int i = str.length() - ; ; ){
if(str[i] == '#'){
str = str.substr(, i - );
i = str.length() - ;
}else{
break;
}
}
return str;
} // Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if(!data.size()) return NULL;
vector<string> dataVec;
int sz = data.length();
for(int i = ; i < sz;){//分割字符串,保存到vector中
if(data[i] != ','){
int j = i;
for(; j < sz && data[j] != ','; ++j)
;
string tmp = data.substr(i, j - i);//注意substr的使用细节
dataVec.push_back(tmp);
i = j + ; //跳过','符号
}
}
sz = dataVec.size();
TreeNode * root = new TreeNode(atoi(dataVec[].c_str()));
queue<TreeNode *>q;
q.push(root);
int i = ;
while(!q.empty() && i < sz){
TreeNode * t = q.front();
if(dataVec[i] != "#"){
t->left = new TreeNode(atoi(dataVec[i].c_str()));
q.push(t->left);
}else{
t->left = NULL;
}
i++;
if(i >= sz) break;
if(dataVec[i] != "#"){
t->right = new TreeNode(atoi(dataVec[i].c_str()));
q.push(t->right);
}else{
t->right = NULL;
}
q.pop();
i++;
}
return root;
}
};

吐槽一下,c++连个split函数都没有,写起来真是恶心,还要自己去分割字符串。

上一篇:最新的JavaScript核心语言标准——ES6,彻底改变你编写JS代码的方式!【转载+整理】


下一篇:filebeat配置文件