/**
* 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 {
private:
string ans;
string null="null";
TreeNode *root=NULL;
void makeTree(string &data,int &i,TreeNode* &root){// TreeNode* &中,&不能少
string item;// item="" 而不是NULL
while(data[i]!=' ' && i<data.size()) item+=data[i++];
if(item==null) return;
stringstream ss;
int val;
ss<<item;
ss>>val;
root =new TreeNode(val);
makeTree(data,++i,root->left);//++i 空格跳过
makeTree(data,++i,root->right);// ++i 空格跳过
}
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
stringstream ss;
string str;
if(ans!="") ans+=' ';
if(root==NULL){
ans+=null;
return ans;
}
ss<<root->val;
ss>>str;
ans+=str;
serialize(root->left);
serialize(root->right);
return ans;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
int i=0;
makeTree(data,i,root);// 不能直接写成makeTree(data,0,root);
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
Serialize and Deserialize Binary Tree
最新推荐文章于 2024-03-29 12:06:01 发布