297. Serialize and Deserialize Binary Tree

来源:互联网 发布:js 0 100两位小数 编辑:程序博客网 时间:2024/05/22 15:15
/** * 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:    void serialize(TreeNode *root,ostringstream &out)    {        if(root)        {            out<<root->val<<" ";            serialize(root->left,out);            serialize(root->right,out);        }        else        {            out<<"#"<<" ";        }    }    TreeNode *deserialize(istringstream &in)    {        string s;        in>>s;        if(s!="#")        {            TreeNode *root=new TreeNode(stoi(s));            root->left=deserialize(in);            root->right=deserialize(in);            return root;        }        else        {            return nullptr;        }    }public:    // Encodes a tree to a single string.    string serialize(TreeNode* root) {        ostringstream out;        serialize(root,out);        return out.str();    }    // Decodes your encoded data to tree.    TreeNode* deserialize(string data) {        istringstream in(data);        return deserialize(in);    }};// Your Codec object will be instantiated and called as such:// Codec codec;// codec.deserialize(codec.serialize(root));
1 0
原创粉丝点击