0211 花一分钟和一辈子看透事物本质的人,过的并非同样的生活

LC297

class Codec
{
public:
//Encode a tree to a single string.
string serialize(TreeNode* root)
    {
    ostringstream out;
    serialize(root,out);
    //str() 返回ostringsteam里的临时值
    return out.str();

    }//es
TreeNode* deserialize(string data)
    {
        istringstream in(data);
        return deserialize(in);
    }
private:
    void serialize(TreeNode* root,ostringstream& out)
    {
        if(!root)
        {
            out<<"# ";
            return;
        }
        out<<root->val<<" ";
        serialize(root->left,out);
        serialize(root->right,out);
    }

TreeNode* deserialize(istringstream& in)
    {
        string val;
        in>>val;
        if(val=="#") return nullptr;
        TreeNode* root=new TreeNode(stoi(val));
        root->left=deserialize(in);
        root->right=deserialize(in);
        return root;
    }
};

猜你喜欢

转载自www.cnblogs.com/Marigolci/p/12293742.html