题解 | #序列化二叉树#
序列化二叉树
https://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return char字符型一维数组
*/
char* Serialize(struct TreeNode* root ) {
// write code here
//层序
if(!root) return NULL;
char* str = (char*)malloc(sizeof(char)*300);
struct TreeNode** pr = (struct TreeNode**)malloc(sizeof(struct TreeNode*)*100);
int p1 = -1 , p2 = -1 , pa = -1;
pr[++p1] = root;
while(p1 != p2){
root = pr[++p2];
if(root){
str[++pa] =root->val;
pr[++p1] = root->left;
pr[++p1] = root->right;
}
else{
str[++pa] = '#';
}
}
str[++pa] = '\0';
free(pr);
return str;
}
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param str char字符型一维数组
* @return TreeNode类
*/
struct TreeNode* Deserialize(char* str ) {
// write code here
if(!str) return NULL;
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
struct TreeNode* pro[100];
int p1 = -1 , p2 = -1;
root->val = (int)*str;
str++;
pro[++p1] = root;
while(*str != '\0'){
struct TreeNode* t = pro[++p2];
if(*str != '#'){
struct TreeNode* r = (struct TreeNode*)malloc(sizeof(struct TreeNode));
r->val = (unsigned char)*str;
pro[++p1] = r;
t->left = r;
}
else{
t->left = NULL;
}
str++;
if(*str != '#'){
struct TreeNode* r = (struct TreeNode*)malloc(sizeof(struct TreeNode));
r->val = (unsigned char)*str;
pro[++p1] = r;
t->right = r;
}
else{
t->right = NULL;
}
str++;
}
return root;
}
