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; } };
原文地址:https://www.cnblogs.com/Marigolci/p/12293742.html
时间: 2024-10-09 18:25:11