LeetCode 297. Serialize and Deserialize Binary Tree
树的序列化,
/**
* 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:
string find(string s,int pos)
{
string str="";
for(int i=pos;i<s.length();i++)
{
if(s[i]==',')
break;
str +=s[i];
}
return str;
}
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string s="";
fun2(root,s);
return s;
}
void fun2(TreeNode* root,string& res)
{
if(root!=NULL)
{
res+=to_string(root->val);
res+=',';
fun2(root->left,res);
res+=',';
fun2(root->right,res);
}
else
{
res+='.';
}
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
TreeNode* root=NULL;
fun(data,root,0);
return root;
}
int fun(string data,TreeNode* &tree,int pos)
{
string s = find(data,pos);
if(s[0]=='.')
{
tree=NULL;
return pos+s.length()+1;
}
else
{
tree = new TreeNode(atoi(s.c_str()));
int x = fun(data,tree->left,pos+s.length()+1);
int y = fun(data,tree->right,x);
return y;
}
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));