//二叉树的先序序列化,与反序列化
class TreeNode
{
public:
int val;
TreeNode *parent;
TreeNode*left;
TreeNode* right;
TreeNode(int x) { this->val = x; this->parent = NULL;
this->left = NULL; this->right = NULL; }
};
typedef class TreeNode *Tree;
string Pre(Tree head)//先序序列化
{
if (head == NULL)
return "#_";
string res = to_string(head->val) + "_";
Pre(head->left);
Pre(head->right);
return res;
}
Tree Rev(string s)
{
if (s == "#_")
return NULL;
stringstream ss(s);//string转换成string流;
queue<string>q;//二叉树序列化之后的字符串放到队列当中
string stem;
while (getline(ss, stem, '_'))//使用getline函数去掉”-”符
{
q.push(stem);
}
return Recon(q);
}
Tree Recon(queue<string>&q)
{
string val = q.front();
q.pop();
if (val == "#")
return NULL;
Tree cur = new TreeNode(stoi(val));//使用stoi函数把string类型转换成int类型
cur->left = Recon(q);
cur->right = Recon(q);
return cur;
}
二叉树的序列化与反序列化
最新推荐文章于 2024-07-18 18:08:02 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)