转自https://www.nowcoder.com/profile/6475323/codeBookDetail?submissionId=19293787
与https://blog.csdn.net/YF_Li123/article/details/70237074
题目描述
请实现两个函数,分别用来序列化和反序列化二叉树
序列化结果存放于数组中
class Solution {
public:
vector<int> buf;
void dfs1(TreeNode *root)
{
if(!root) buf.push_back(0xFFFFFFFF);
else
{
buf.push_back(root->val);
dfs1(root->left);
dfs1(root->right);
}
}
TreeNode* dfs2(int* &p)
{
if(*p == 0xFFFFFFFF)
{
p++;
return NULL;
}
TreeNode* res = new TreeNode(*p);
p++;
res->left = dfs2(p);
res->right = dfs2(p);
return res;
}
char* Serialize(TreeNode *root) {
buf.clear();
dfs1(root);
int bufSize = buf.size();
int *res = new int[bufSize];
for(int i = 0; i < bufSize; i++)
res[i] = buf[i];
return (char*)res;
}
TreeNode* Deserialize(char *str) {
int* p = (int*)str;
return dfs2(p);
}
};
序列化结果存放于字符串中
class Solution {
public:
/*=========================二叉树序列化==============================*/
char* Serialize(TreeNode *root) {
if (root == NULL)
return NULL;
string str;
serialize(root, str);
char* buffer = new char[str.size() + 1];
strcpy(buffer, str.c_str()); //将string类型的字符串转换成C_style类型并复制到一个char类型数组
return buffer;
}
void serialize(TreeNode* root, string& str)
{
if (root == NULL)
{
str += "$,"; //叶子结点的左右子结点为空则用 $ 来代替
return;
}
str += to_string(root->val); //将结点值(int)转换成字符串(string)类型
str += ',';
serialize(root->left, str); //递归序列化结点的左子树
serialize(root->right, str); //递归序列化结点的右子树
}
/*========================二叉树反序列化============================*/
TreeNode* Deserialize(char *str) {
if (str == NULL)
return NULL;
return deserialize(&str);
}
TreeNode* deserialize(char** str)
{
if (**str == '$')
{
(*str) += 2;
return NULL;
}
int val = 0;
while (**str != ','&&**str != '\0') //把字符串类型的数字转换成int类型的数字
{
val = val * 10 + (**str - '0');
++(*str);
}
TreeNode* root = new TreeNode(val); //构建根结点
if (**str == '\0')
return root;
else
++(*str);
root->left = deserialize(str); //递归的构建左子树结点
root->right = deserialize(str); //递归的构建右子树结点
return root;
}
};
DFS与BFS