/**
* 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:
string serialize(TreeNode* root)
{
ostringstream out;//定义ostringstream类型,将字符串输入至out中
serialize(root, out);
return out.str();
}
void serialize(TreeNode*root,ostringstream& out)
{
if(root==nullptr)
{
out<<"$ ";
}
else
{
out<<root->val<<' ';
serialize(root->left,out);
serialize(root->right,out);
}
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data)
{
istringstream in(data);//istringstream,从string中读取字符,以空格为界
return deserialize(in);
}
TreeNode* deserialize(istringstream& in)
{
string str;
in >> str;
if(str == "$") return nullptr;
TreeNode* node = new TreeNode(stoi(str));
node->left = deserialize(in);
node->right = deserialize(in);
return node;
}
};
面试题37:序列化二叉树
最新推荐文章于 2021-03-01 22:09:02 发布