二叉树的序列化和反序列化
程序员文章站
2022-03-12 17:10:46
...
- 题目描述
请实现两个函数,分别用来序列化和反序列化二叉树
二叉树的序列化是指:把一棵二叉树按照某种遍历方式的结果以某种格式保存为字符串,从而使得内存中建立起来的二叉树可以持久保存。序列化可以基于先序、中序、后序、层序的二叉树遍历方式来进行修改,序列化的结果是一个字符串,序列化时通过 某种符号表示空节点(#),以 ! 表示一个结点值的结束(value!)。
二叉树的反序列化是指:根据某种遍历顺序得到的序列化字符串结果str,重构二叉树。
例如,我们可以把一个只有根节点为1的二叉树序列化为"1,",然后通过自己的函数来解析回这个二叉树;
#include<iostream>
#include<vector>
#include<algorithm>
#include<cstring>
#include<sstream>
#include<cmath>
#include<unordered_map>
#include <bitset>
using namespace std;
struct TreeNode
{
int val;
struct TreeNode* left;
struct TreeNode* right;
TreeNode(int x): val(x),left(nullptr),right(nullptr){};
};
class Solution {
public:
string sHelper(TreeNode *node)
{
if (node == NULL)
return "#";
return to_string(node->val) + "," +
sHelper(node->left) + "," +
sHelper(node->right);
}
char* Serialize(TreeNode *root)
{
string s = sHelper(root);
cout<<"s:"<<s<<endl;
char *ret = new char[s.length() + 1];
strcpy(ret, const_cast<char*>(s.c_str())); //c_str()返回一个临时的指针常量,不能对其操作;
cout<<"*ret:"<<*ret<<" "<<"ret:"<<ret<<endl;
return ret;
}
TreeNode *dHelper(stringstream &ss)
{
string str;
getline(ss, str, ','); //从输入流中读取到输出流;
cout<<"str: "<<str<<endl;
if (str == "#")
return NULL;
else
{
TreeNode *node = new TreeNode(stoi(str)); //stoi将n为字符串转化为10进制的;
node->left = dHelper(ss);
node->right = dHelper(ss);
return node;
}
}
TreeNode* Deserialize(char *str) {
stringstream ss(str);
cout<<"ss:"<<ss.str()<<endl;
return dHelper(ss);
}
};
int main() {
TreeNode* treeNode1 = new TreeNode(1);
TreeNode* treeNode2 = new TreeNode(2);
TreeNode* treeNode3 = new TreeNode(3);
TreeNode* treeNode4 = new TreeNode(4);
TreeNode* treeNode5 = new TreeNode(5);
TreeNode* treeNode6 = new TreeNode(6);
treeNode1->left = treeNode2;
treeNode1->right = treeNode3;
treeNode2->left = treeNode4;
treeNode3->left = treeNode5;
treeNode3->right = treeNode6;
Solution sol;
char* str = sol.Serialize(treeNode1);
TreeNode* treeNode = sol.Deserialize(str);
}
- 构建的二叉树为:
- 输出结果:中根遍历
上一篇: (数据结构与算法)冒泡排序和选择排序
下一篇: String Compression