您的位置:首页 > 理论基础 > 数据结构算法

【二叉树】树的序列化和反序列化【449. Serialize and Deserialize BST】

2017-07-14 09:40 429 查看
题目链接:https://leetcode.com/problems/serialize-and-deserialize-bst/#/description

树的序列化与反序列化(看完有惊喜0.0)

序列化参照https://leetcode.com/problems/construct-string-from-binary-tree/#/description

将树[2,1,3]转化成2(1)(3)格式

反序列化将2(1)(3)拆分,2->跟节点,(2)->左子树,(3)->右子树,递归解之

/**
* 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) {
if(root==NULL) return "";
string s=to_string(root->val);
if(root->left==NULL&&root->right==NULL) return s;
if(root->left==NULL){
s+="()";
if(root->right)
s+='('+serialize(root->right)+')';
}else{
s+='('+serialize(root->left)+')';
if(root->right!=NULL){
s+='('+serialize(root->right)+')';
}
}
// cout<<s<<endl;
return s;
}

// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if(data==""||data=="()") return NULL;
TreeNode* node = new TreeNode(NULL);
//  左子树起始位置
int t1=data.find_first_of('(');
if(t1==-1){
node->val=stoi(data);
node->left=NULL;
node->right=NULL;
return node;
}else{
node->val=stoi(data.substr(0,t1));
}
//  右子树起始位置
int t2=0;
int cnt=1;      //  记录'('的个数 括号匹配
int len=data.size();
for(int i=t1+1;i<len;i++){
if(data[i]=='(') cnt++;
if(data[i]==')') cnt--;
if(cnt==0){
t2=i;
break;
}
}
// cout<<t1<<' '<<t2<<endl;
string s1=data.substr(t1+1,t2-t1-1);
string s2="";
if(data.find_first_of('(',t2)!=string::npos)s2=data.substr(t2+2,data.find_last_of(')')-t2-2);
// cout<<s1<<' '<<s2<<endl;
node->left=deserialize(s1);
node->right=deserialize(s2);
return node;
}
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));


数据的测试方法摆在那里,0.0,我们轻松的投机一下Orz,弱渣的解题技巧

/**
* 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:

TreeNode* node = new TreeNode(NULL);
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string s="";
node = root;
return s;
}

// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
return node;
}
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息